First, let’s take a look at the official explanation of call(), “Call a method of an object and replace the current object with another object.” After reading this explanation, you may be even more confused. See example:
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 to pop up the value of variable x contained in the current pointer
function f(){
alert (this.x);
}
//The return value is "I declared it in the function class structure a"
f.call(new a());
My understanding is that f.call(new a()) copies the function (actually also an object) f to the called object "new a()" for analysis. In fact, the analysis result is the same as the following code:
function a(){
this.x = "I declared it in function class structure a";
alert(this.x);
}
a();
It’s just that the scope of variable In the above example, f is completely inherited by the object of constructor a. If this is not enough to show that a.call(b) is an inheritance pattern, then let's look at a usage that is more inheritance-flavored.
function f(){
This.a ="a";
This.b = function(){
alert("b");
}
}
function e(){
f.call(this);
}
var c = new e();
alert(c.a); //Pop up a
c.b(); //Pop up b
In this example, anyone who knows how to use a browser can see that e completely inherits the attributes and methods of f. Otherwise, it is inexplicable, because the attributes a and b are not defined in e, so it is common sense to infer that In the instance object c of e, these two attributes will not appear.