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
}         

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM