xiaokeqi / i-learned

1 stars 0 forks source link

借助apply实现bind #33

Open xiaokeqi opened 4 years ago

xiaokeqi commented 4 years ago

Function.prototype._bind = function(context){ let self = this;// 调用的函数,如function test() return function(){ self.apply(context,arguments) } }

xiaokeqi commented 4 years ago

function test(){console.log(this.y,'from obj')} var obj = {y:'xiaokeqi'} var r = test._bind(obj) r();

执行结果:‘xiaokeqi from obj’

xiaokeqi commented 4 years ago

注意: test instanceof Function //true 故 test.bind 中的this指向是函数test, this并不一定全部是对象类型,也可以是function类型 所以最后执行self.apply方法即可