当前位置:网站首页>[JS] usage of call (), apply (), bind ()

[JS] usage of call (), apply (), bind ()

2022-07-20 08:47:00 one or only

Introduce & summary

1、call、apply And bind all Used to change this binding .
2、call、apply Changing this While pointing, it will Execute function , disposable . The difference is call Method passes function call parameters in Hash form , and apply Methodical The formal parameter is an array . In the case of parameter passing ,call The performance is higher than apply, because apply At the time of execution, we need to further parse the array .
3、bind Changing this After is Return a new binding function , That is, return a new function , Do not execute functions directly . And after that this The direction of cannot pass through call、apply、bind change .

example 1

obj.objAge;  // 17
obj.myFun()  //  Xiao Zhang's age  undefined

example 2

shows()  //  Blind monk  

Compare the two this The difference between , The first one to print it this Point to obj, The second globally declared shows() function this yes window .

1、call()、apply()、bind() It's all about redefining this Of this object !

Such as :

obj.myFun.call(db);    //  Dema's age  99
obj.myFun.apply(db);    //  Dema's age  99
obj.myFun.bind(db)();   //  Dema's age  99

What's more bind There's a lot more behind the method () Outside , The results are consistent !

From this we come to the conclusion that ,bind Back to a New functions , You have to call it to be executed .

2、 contrast call 、bind 、 apply In this case

obj.myFun.call(db,' Chengdu ',' Shanghai ');  //  Dema   Age  99   come from   Chengdu to Shanghai 
obj.myFun.apply(db,[' Chengdu ',' Shanghai ']);  //  Dema   Age  99   come from   Chengdu to Shanghai   
obj.myFun.bind(db,' Chengdu ',' Shanghai ')();   //  Dema   Age  99   come from   Chengdu to Shanghai 
obj.myFun.bind(db,[' Chengdu ',' Shanghai '])(); //  Dema   Age  99   come from   Chengdu ,  Shanghai to  undefined

summary : 

It's not hard to see from the above four results :

call 、bind 、 apply Of these three functions The first parameter is this Point to object of , The second parameter difference is :

call The parameters of are put in directly , Second, third, third n Parameters are all separated by commas , Put it right in the back  obj.myFun.call(db,' Chengdu ', ... ,'string' ).

apply All parameters of must be placed in one Array Pass it in  obj.myFun.apply(db,[' Chengdu ', ..., 'string' ]).

bind Except that the return is a function , Its parameters and call equally .

Of course , The three parameters are not limited to string type , It's allowed to be all kinds of , Include function 、 object wait !

原网站

版权声明
本文为[one or only]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/201/202207190503394875.html