bind()
方法:
會創建一個新函數。當這個新函數被調用時,bind()
的第一個參數將作爲它運行時的 this
,之後的一序列參數將會在傳遞的實參前傳入作爲它的參數。
此外,bind
實現需要考慮實例化後對原型鏈的影響。
Function.prototype.bind2 = function(content) {
if(typeof this != "function") {
throw Error("not a function")
}
// 若沒問參數類型則從這開始寫
let fn = this;
let args = [...arguments].slice(1);
let resFn = function() {
return fn.apply(this instanceof resFn ? this : content,args.concat(...arguments) )
}
function tmp() {}
tmp.prototype = this.prototype;
resFn.prototype = new tmp();
return resFn;
}