[英]Javascript bind Function Implementation
我想為不支持綁定功能的瀏覽器的 javascript 綁定功能創建 Polyfill。 任何人,請告訴綁定函數是如何在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();
為了簡單起見,在使用現代 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);
}
}
一個簡單的解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.