JavaScript基础之--- 手写 bind 方法的实现

 

bind方法

bind()方法 返回一个新函数;新函数newFn 与被调用函数fn 具有相同的函数体。

let newFn = fn.bind(context,arg1,arg2,..)

就是将fn方法添加到conetxt的属性中,fn 中的this 指向 context;即 context.fn()

  • tcontext:当函数被调用时,该参数会作为原函数运行时的this指向;当使用new操作符调用绑定函数时,该参数无效。
  • 之后的一序列参数将会在传递的实参前传入作为它的参数。
  • bind方法返回的函数作为构造函数的时候:bind执行时绑定的this会失效,但传入的参数依然生效。 (参考下面的:new例子)

 

bind方法实现的思路:

  1. bind 方法不会立即执行,需要返回一个待执行的函数;(闭包)
  2. 实现作用域绑定(apply)
  3. 参数传递(apply 的数组传参)
  4. 当作为构造函数的时候,进行原型继承

 

最终方法的实现:

Function.prototype.myBind = function() {
   if(typeOf(this) !== 'function') {
      throw new Error('not a function!!');
   }
    let self = this;
    let args = [ ...arguments ].slice(1);
    let bound = function() {
        let _this = this.instanceof bound ? this : context;
        self.apply(_this, [...args, ...arguments])
    }

    let Fn = function() {}
    Fn.prototype = this.prototype
    bound.prototype = new Fn()
    return bound
}         

 

 

 

 

 

 

posted @ 2020-03-30 11:12  见证LBJ  阅读(2291)  评论(0编辑  收藏  举报