这里我们使用apply(),简单实现一下bind();
首先我们得了解bind()的定义:
创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
所以最终返回的是一个function,并且需要用apply()来修改this指向和传参。
上代码
Function.prototype.bind = function (content, ...args) {
var self = this;
return function () {
return self.apply(content, args);
}
}
测试使用
var module = {
x: 42,
getSite: function(y, z) {
return `${this.x},${y},${z}`;
}
};
var getSiteCopy = module.getSite;
var getSiteBind = getSiteCopy.bind(module, 142, 21);
console.log(getSiteBind ()); // 42,142,21
既然已经用apply()实现了bind,如果call() 实现呢?也是差不多的。
Function.prototype.bind = function (...args) {
var self = this;
return function () {
return self.call(...args);
}
}
运行截图
以上使用了apply()/call()实现了bind(),但是还是借助call()/apply(),那么我们能不能也实现一下call()/apply()呢?
ps: 转载请注明出处