Let’s first take a look at the official explanation about call(), “Calling one method of an object and replacing the current object with another object.” After reading this explanation, you may be even more confused. See example:
The code copy is as follows:
var x = "I am a global variable"; //Define global variable x
function a(){ //Define function class structure a
this.x = "I declared it in function class structure a";
}
//Define a normal function and pop up the value of the variable x contained in the current pointer.
function f(){
alert (this.x);
}
//The return value is "I declared in function class structure a"
f.call(new a());
My understanding is that f.call(new a()) is to copy the function (actually an object) f to the called object "new a()" for parsing. In fact, it is the same as the parsing result of the following code:
The code copy is as follows:
function a(){
this.x = "I declared it in function class structure a";
alert(this.x);
}
a();
It’s just that the scope of variable X is different at this time. Yes... it seems to have a bit of inheritance, isn’t it? In the above example, f is completely inherited by the strength object of constructor a. If this is not enough to show that a.call(b) is an inheritance mode, then let's look at a more inherited usage.
The code copy is as follows:
function f(){
this.a ="a";
this.b = function(){
alert("b");
}
}
function e(){
f.call(this);
}
var c = new e();
alert(ca); //Popt a
cb(); //Popt b
In this example, as long as friends who know how to use the browser, they can see that e completely inherits the properties and methods of f, otherwise it will not be explained, because attributes a and b are not defined in e. Then, according to common sense, these two properties will not appear in the instance object c of e.