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方法實現的思路:
- bind 方法不會立即執行,需要返回一個待執行的函數;(閉包)
- 實現作用域綁定(apply)
- 參數傳遞(apply 的數組傳參)
- 當作為構造函數的時候,進行原型繼承
最終方法的實現:
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 }