This article mainly introduces the magical call () method in JavaScript. This article uses simple languages to help you better understand the call () method. For more information about call (), see () "Call a method of an object and replace the current object with another object. ", After reading this explanation, you may be confused. Example:
The Code is as follows:
Var x = "I Am a global variable"; // defines the global variable x
Function a () {// define function class structure
This. x = "I declare it in function class structure ";
}
// Define a common function. The value of variable x contained in the current pointer is displayed.
Function f (){
Alert (this. x );
}
// The returned value is "I declare it in function class structure"
F. call (new ());
In my understanding, f. call (new a () is to copy 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 is as follows:
Function (){
This. x = "I declare it in function class structure ";
Alert (this. x );
}
A ();
In this case, variable X has different scopes... It looks a little inherited, isn't it? In the preceding example, f is fully inherited by the strength object of constructor a. If this is not enough, it means. call (B) is an inheritance mode, so let's look at a more inherited usage.
The Code is as follows:
Function f (){
This. a = "";
This. B = function (){
Alert ("B ");
}
}
Function e (){
F. call (this );
}
Var c = new e ();
Alert (c. a); // pop up
C. B (); // pop up B
In this example, as long as a friend of the browser can see that e fully inherits the attributes and methods of f, otherwise it cannot be explained, because attributes a and B are not defined in e, it is inferred from common sense that these two attributes will not appear in Instance Object c of e.