如何用apply实现一个bind

48 阅读1分钟

Function.prototype._bind = function(target) {

// 保留调用_bind方法的对象
let _this = this;
// 接收保存传入_bind方法中的参数,等价于arguments.slice(1),除了第一个参数其余全视作传入参数
let args = [].slice.call(arguments, 1)
return function() {
    return _this.apply(target, args)
}

}

let obj = { name: '测试员小陈' }

// 测试函数 function test(args) { console.log('this:', this); console.log('名字:', this.name); console.log('参数:', args); }

console.log(test._bind(obj, "I am args")); // output: [Function]

test._bind(obj, "csj")()

/* 执行结果

  • this: { name: '测试员小陈' }
  • 名字: 测试员小陈
  • 参数: csj */