call apply bind 相關認識

2021-10-07 12:11:32 字數 3056 閱讀 8768

1、 這兩個東西可以執行函式

function

play

(a,b)

// 可以執行函式

play.

call()

;play.()

;

2、(重要)這兩個玩意可以改變this 的指向

fn.

call

(obj)

;//將函式中this的指向改變為這裡帶入的第乙個引數obj

// 函式中如果沒有this,call就沒有任何意義了,和普通的執行函式概念一樣

fn.

call

(obj,3,

5);//call在執行函式時,函式的引數從第二位開始依次寫入

fn.(obj,[3

,5])

;

試一試:

var obj=

}obj.

abc(3,

5);//obj物件的a屬性變為3,b屬性變為5

var o1=

;//新建o1物件

obj.abc.

call

(o1,3,

5);//執行obj.abc並且改變其中this的指向到o1,帶入3,5

obj.abc.

(o1,[3

,5])

;console.

log(obj)

;// obj新增了屬性

// o1也新增了屬性

obj.abc.

call

(null,3

,5);

//與下面語句同樣

obj.abc.

(null,[

3,5]

);// obj.abc.call(window,3,5);

console.

log(a,b)

;//3 5 值在window上

//封裝乙個math.max方法獲得陣列的最大值

var math=

return max;}}

//執行

var arr=[1

,3,5

,6]var max=math.max.

(null

,arr)

;//因為math.max沒有this,null,傳入以後並沒有任何作用,目的是傳參時傳入的是陣列

注意

call

function.prototype.

mycall

=function

(context)}*/

context.fn =

this

;// 2.儲存返回值

let result ='';

// 3.取出傳遞的引數 第乙個引數是this, 下面是三種擷取除第乙個引數之外剩餘引數的方法(解決問題1)

const args =

[...arguments]

.slice(1

);//const args = array.prototype.slice.call(arguments, 1);

//const args = array.from(arguments).slice(1);

// 4.執行這個方法,並傳入引數 ...是es6的語法用來展開陣列

result = context.fn(

...args)

;//這裡主要利用了,物件中的屬性函式中,this指向該物件

//5.刪除該屬性

delete context.fn;

//6.返回

return result;

}const obj =

function

fn(name, age)

}fn.

mycall

(obj,

'lj',25

);//

function.prototype.

=function

(context, args)

else

delete context.fn;

return result;

}const obj =

function

fn(name, age)

}fn.

(obj,

['lj',25

]);//

複製**

bind() 方法建立乙個新的函式,在 bind() 被呼叫時,這個新函式的 this 被指定為 bind() 的第乙個引數,而其餘引數將作為新函式的引數,供呼叫時使用(mdn)

bind 特性:

因為bind方法的引數包含在兩個地方,fn.bind(obj,a,b)(c,d),這裡abcd都是引數,所以這裡我們需要通過柯里化將參進行拼接,下面就是bind的重寫

function.prototype.

mybind

=function

(context)

const self =

this

;//通過self來儲存呼叫函式this

const args1 =

[...arguments]

.slice(1

)//引數1,將context除外的引數進行擷取出來

const

bindfn

=function()

return bindfn

}const obj =

function

fn(name, age)

}var result = fn.

mybind

(obj)

('lu',25

)console.

log(result)

call, apply, bind方法詳解

function a x,y var c a.call c,5,6 5 6 arguments 5,6 再看例子 function person age,male var person1 person.call person1,20,female person1 var person var per...

手寫call,apply,bind函式

涉及面試題 考慮兩點 function.prototype.mycall function context context context window 和上面的 一樣 context.fn this const args arguments slice 1 const result context...

call apply bind方法詳解

var name window var newthis function showname info1,info2 showname a b 輸出 window a b 通過bind改變this指向 var newshowname showname.bind newthis,hello world ...