手寫 call apply 及 bind 函式

2021-10-05 15:33:47 字數 1220 閱讀 3281

function.prototype.

mycall

=function

(context)

context = context || window;

context.fn =

this

;//建立fn屬性,並將值設定為需要呼叫的函式

const args =

[...arguments]

.slice(1

);//因為call可以傳入多個引數作為呼叫函式的引數,所以要將引數剝離

const result = context.fn(

...args)

;//呼叫函式

delete context.fn;

//將物件上的函式刪除

return result;

};

function.prototype.

=function

(context)

context = context || window;

context.fn =

this

;//建立fn屬性,並將值設定為需要呼叫的函式

let result;

//處理引數和 call 有區別

if(arguments[1]

)else

delete context.fn;

return result;

};

function.prototype.

mybind

=function

(context)

const _this =

this

;const args =

[...arguments]

.slice(1

);//返回乙個函式

return

functionf(

)return _this.

(context,args.

concat

(...arguments));

// 對於引數需要注意的是:因為bind可以實現.bind(obj, 1)(2),所以我們需要將兩邊的引數拼接起來,

// 於是就有了這樣的實現 args.concat(...arguments)}}

;

以上內容結合個人理解與相關資料,如有錯誤,請批評指正。

JS容易混淆的call apply和bind方法

詳情描述 共同點call 定義 呼叫乙個物件的乙個方法,用另乙個物件替換當前物件 理解 method1.call method2,num1,num2 method1 num1,num2 即用method1替換method2 例子 function animal function dog var an...

call apply及bind的實現原理

2.call的實現原理 我們知道,函式都可以呼叫call,說明call是函式原型上的方法,所有的例項都可以呼叫。即 function.prototype.call 其次,如果第乙個引數沒有傳入,在全域性環境下,那麼預設this指向window 瀏覽器 global node 非嚴格模式 傳入call...

call,apply和bind的用法及區別

callfunction fn x,y console.log x y 11 var obj 語法 fn.call obj,2,9 應用 var obj array.prototype.push.call obj,30 console.log obj call obj,0,2 console.log...