The Magic Call () method in JavaScript _javascript tips

Source: Internet
Author: User
Tags magic call

Take a look at the official interpretation of call (), "one method of calling an object, replacing the current object with another object." "You may be more puzzled by this explanation," he said. See Example:

Copy Code code as follows:

var x = "I am a global variable"; Define global variable X
function A () {///define functional class structure a
This.x = "I am in the function class structure a declaration of OH";
}
Defines a normal function that pops the value of the variable x contained in the current pointer
function f () {
alert (this.x);
}
The return value is "I declare it in function class structure A."
F.call (New A ());

My understanding is that F.call (new A ()) is simply copying the function (which is also object) F to the called object "new A ()" To resolve it, in fact, as in the following code parsing result:
Copy Code code as follows:

function A () {
This.x = "I am in the function class structure a declaration of OH";
alert (this.x);
}
A ();

Just now the scope of the variable x is different just ... It looks like a little inherited flavor. In the example above, F is completely inherited by the power object of constructor A, and if that's not enough to show that A.call (b) is an inheritance pattern, then look at a more inherited flavor.
Copy Code code 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 A
C.B (); Eject b

In this case, as long as a friend of the browser can see that e completely inherits the properties and methods of F, otherwise it cannot be explained, because there is no definition of properties A and B in E, so it is common sense to infer that the two properties do 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.