MAGIC call () method in JavaScript _ javascript skills

Source: Internet
Author: User
Tags magic call
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.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.