0
点赞
收藏
分享

微信扫一扫

在 JavaScript 中如何自定义 bind 函数

IT影子 2022-03-30 阅读 92


Function.prototype.customBind = function (context) {
var fn = this,
args = Array.prototype.slice.call(arguments, 1);
return function() {
// 将新函数执行时的参数 arguments 全部数组化,然后与绑定时传参 arg 合并
var newArgs = Array.prototype.slice.call(arguments);
return fn.apply(context, args.concat(newArgs));
}
};
var testFn = function(obj, arg) {
console.log('作用域对象属性值:' + this.value);
console.log('绑定函数时参数对象属性值:' + obj.value);
console.log('调用新函数参数值:' + arg);
}
var testObj = {
value: 1
};
var newFn = testFn.customBind(testObj, {value: 2});
newFn('hello world’);


举报

相关推荐

0 条评论