What do call, apply, and bind do? Why should we learn this?
is generally used to specify the environment of this. Before you learn it, you will usually have these problems.
var a = { user:"追梦子", fn:function(){ console.log(this.user); } } var b = a.fn; b(); //undefined
We want to print the user in object a but why it prints out undefined? It is ok if we execute a.fn() directly.
var a = { user:"追梦子", fn:function(){ console.log(this.user); } } a.fn(); //追梦子
You can print here because this here points to function a, so why doesn’t the above point to a? If we need to understand the pointing problem of this, please see the thorough understanding of this pointing in js
Although this method can achieve our purpose, sometimes we have to save this object to another In a variable, you can use the following method.
1. call()
##
var a = { user:"追梦子", fn:function(){ console.log(this.user); //追梦子 } } var b = a.fn; b.call(a);
In addition to the first parameter, the call method can also add multiple parameters, as follows:
var a = { user:"追梦子", fn:function(e,ee){ console.log(this.user); //追梦子 console.log(e+ee); //3 } } var b = a.fn; b.call(a,1,2);
2. apply()
var a = { user:"追梦子", fn:function(){ console.log(this.user); //追梦子 } } var b = a.fn; b.apply(a);
var a = { user:"追梦子", fn:function(e,ee){ console.log(this.user); //追梦子 console.log(e+ee); //11 } } var b = a.fn; b.apply(a,[10,1]);
var a = { user:"追梦子", fn:function(e,ee){ console.log(this.user); //追梦子 console.log(e+ee); //520 } } var b = a.fn; var arr = [500,20]; b.apply(a,arr); //注意如果call和apply的第一个参数写的是null,那么this指向的是window对象
var a = { user:"追梦子", fn:function(){ console.log(this); //Window {external: Object, chrome: Object, document: document, a: Object, speechSynthesis: SpeechSynthesis…} } } var b = a.fn; b.apply(null);
3. bind()
var a = { user:"追梦子", fn:function(){ console.log(this.user); } } var b = a.fn; b.bind(a);
var a = { user:"追梦子", fn:function(){ console.log(this.user); } } var b = a.fn; var c = b.bind(a); console.log(c); //function() { [native code] }
var a = { user:"追梦子", fn:function(){ console.log(this.user); //追梦子 } } var b = a.fn; var c = b.bind(a); c();
var a = { user:"追梦子", fn:function(e,d,f){ console.log(this.user); //追梦子 console.log(e,d,f); //10 1 2 } } var b = a.fn; var c = b.bind(a,10); c(1,2);
Summary: call and apply both change this in the context and execute the function immediately. The bind method allows the corresponding function to decide when It depends on when to call it, and parameters can be added during execution. This is their difference. You can choose to use it according to your actual situation.
The above is the detailed content of What do call, apply, and bind do in JavaScript? Why use them?. For more information, please follow other related articles on the PHP Chinese website!