Function.prototype.pBind = function () {
var self = this; // 保存原函数
var context = [].shift.call(arguments); // 保存需要绑定的this的上下文
var args = Array.prototype.slice.call(arguments); // 剩余的参数转为真数组
console.log('args-------------',args)
/**
* 因为bind 绑定了上下文,因此 self.apply 的第一个参数,是之前我们保存的 context。接下来,我们将
* bind 的其余参数和调用bind后返回的函数在执行的过程中接收的参数进行拼接,作为一个数组传入apply的
* 第二个参数中去。这就完美的实现了 bind 函数的功能
*/
return function () {
console.log('arguments----------', [].slice.call(arguments))
self.apply(context, [].concat.call(args, [].slice.call(arguments)))
}
}
let name = '宋唐', age = 23;
let obj = {
name: '汉秦',
objAge: this.age,
outFun: function (fromW, toGo) {
console.log(`${this.name}: 年龄 ${this.age} 来自${fromW} 去往 ${toGo}`);
}
};
let testObj = {
name: '子瑜',
age: 27
};
obj.outFun.pBind(testObj, '河北', '北京')(); // 子瑜: 年龄 27 来自河北 去往 北京
// obj.outFun.bind(testObj, '河北', '北京')(); // 子瑜: 年龄 27 来自河北 去往 北京
obj.outFun.pBind(testObj, ['河北', '北京'])(2,3); // 子瑜: 年龄 27 来自河北,北京 去往 2
// obj.outFun.bind(testObj, ['河北', '北京'])(2, 3); // 子瑜: 年龄 27 来自河北,北京 去往 undefined
JavaScript实现bind方法
最新推荐文章于 2024-07-26 20:46:33 发布