我希望为不支持 bind 函数的浏览器创建 JavaScript bind 函数的 polyfill。请问有人知道 bind 函数在 JavaScript 中是如何实现的吗?
我希望为不支持 bind 函数的浏览器创建 JavaScript bind 函数的 polyfill。请问有人知道 bind 函数在 JavaScript 中是如何实现的吗?
bind
只是apply
的一个包装器:function bind(fn, thisObj) {
return function() {
return fn.apply(thisObj, arguments);
}
}
使用apply实现bind的基本功能。我称此方法为myBind,将其添加到函数原型中,以便任何函数都可以访问:
函数实现
Function.prototype.myBind = function() {
const callerFunction = this;
const [thisContext, ...args] = arguments;
return function() {
return callerFunction.apply(thisContext, args);
}
用法: 可以作为一个本地绑定函数,接受上下文和参数。
function testMyBind(favColor) {
console.log(this.name, favColor); // Test, pink
}
const user = {
name: 'Test'
}
const bindedFunction = testMyBind.myBind(user, 'pink');
bindedFunction();
Function.prototype.bind = function () {
return () => this.call(...arguments);
};
使用apply
实现基本功能。绑定函数和被绑定的函数都可以接受参数。
Function.prototype.bindPolyfill = function (obj, ...args) {
const func = this;
return function (...newArgs) {
return func.apply(obj, args.concat(newArgs));
};
};
使用方法:
const employee = { id: '2'};
const getEmployee = function(name, dept){
console.log(this.id, name, dept);
};
const employee2 = getEmployee.bindPolyfill(employee, 'test');
employee2('Sales');
Function.prototype.bindPolyfill = function (newThis, ...args) {
return (...newArgs) => {
return this.apply(newThis, [...args, ...newArgs]);
};
};
// Usage
const employee = { id: '2' };
const getEmployee = function (name, dept) {
console.log(this.id, name, dept);
};
const employee2 = getEmployee.bindPolyfill(employee, 'test');
employee2('Sales'); // 2 test Sales
Function.prototype.customBind = function(ctx, ...args) {
const fn = this;
return function() {
return fn.apply(ctx, args);
}
}
if (!Function.prototype.bind) { Function.prototype.bind = function(oThis) { if (typeof this !== 'function') { throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function() {}, fBound = function() { return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { fNOP.prototype = this.prototype; } fBound.prototype = new fNOP(); return fBound; }; }
要点解释: