實現call apply bind,以及他們的區別

2021-10-01 17:43:54 字數 2288 閱讀 7251

三者都是改變this的指向,把函式內this指向了第乙個引數

不同點:

2、傳參區別,第乙個引數都是函式內部this的指向,其餘引數call、bind逐個傳入,

1、三者由函式呼叫,所以線檢查型別

2、根據傳參不同,實現有所區別

call實現

function.prototype.

mycall

=function

(context)

context.fn =

this

;//除第乙個引數,其餘引數是參入的實參

const argus =

[...arguments]

.slice(1

);//呼叫mycall就執行函式,result就是返回值

const result = context.fn(

...argus)

;//把context上面的fn刪除

;//所以在context.fn(arguments[1])

bind實現  bind返回的是改變this的函式

function.prototype.

mybind

=function

(context)

const _this =

this

;const argus =

[...arguments]

.slice(1

);return

function()

}這麼些貌似可以實現,但是我們呼叫可以這樣:fn.

bind

(obj)(1

,2);

所以_this.

(context, argus)引數不全

----

----

----

----

----

----

----

----

----

----

----

----

----

function.prototype.

mybind

=function

(context)

const _this =

this

;const argus =

[...arguments]

.slice(1

);return

function()

}現在看來引數的問題解決了,但是我們還可以這麼用bind

實現call, apply, bind函式

思路 把目標儲存在this中並返回 const obj let name 李四 function add 執行函式 add 李四 add.call obj 張三1.實現call函式定義名稱為mycall function.prototype.mycall function content conte...

手動實現call apply bind

第一種方式 function.prototype.mycall function context,args 第二種方式 function.prototype.mycall2 function context 測試 let person call 我今年 我的工作是 let person1 perso...

call apply bind 實現原理

眾所周知這三個方法都是提供給 函式使用的,函式通過這三個方法呼叫把 this 傳入進去就可以改變其 this 指向。通過這個特性我們可以推斷出 這三個方法都是寫在function物件的原型上的。也就是function.prototype上 下邊我們先在這個原型上寫乙個自己的 call 方法就叫new...