Javascript绑定函数实现



我想为不支持绑定功能的浏览器创建javascript的绑定函数的Polyfill。任何人,请告诉我们绑定函数是如何在javascript中实现的。

在最简单的形式中,bind只是apply:的包装器

function bind(fn, thisObj) {
return function() {
return fn.apply(thisObj, arguments);
}
}

使用apply实现了绑定的基本功能。我调用了这个方法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();

在使用现代JavaScript:的同时保持简单

Function.prototype.bind = function () {
return () => this.call(...arguments);
};

这就是它的全部。

使用apply实现了基本功能。bind函数和绑定函数都可以接受参数。

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);
}
}

一个简单的解决方案

最新更新