Home > Web Front-end > JS Tutorial > body text

The magical call() method in JavaScript_javascript tips

WBOY
Release: 2016-05-16 16:10:06
Original
1110 people have browsed it

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:

Copy code The code 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 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:
Copy code The code 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 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.
Copy code The code is as follows:

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.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template