Explain the running mechanism of JavaScript new _javascript skills

Source: Internet
Author: User
Tags define prototype

Like other high-level languages, JavaScript also has the new operator, and we know that the new operator is used to instantiate a class, allocating an instance object in memory. But in JavaScript, all things are objects, why do they have to be created by new? This article will bring you together to explore the mysteries of new in JavaScript ...

First, recognize the new operator

function Animal (name) {
    this.name = name;
  }
  Animal.color = "BLACK";
  Animal.prototype.say = function () {
    console.log ("I ' m" + this.name);
  };
  var cat = new Animal ("cat");

  Console.log (
    cat.name,//cat
    cat.height//undefined
  );
  Cat.say (); I ' m cat

  console.log (
    animal.name,//animal
    animal.color//back
  );
  Animal.say (); Animal.say is not a function

If you can understand the results of the above output, you have a very good understanding of JS new and this operation mechanism, please ignore this article!

We will deepen your understanding of the new operator in JS by parsing this example! "If you are not aware of JS, please read: JS scope and this keyword"

1, Code interpretation

Line 1-3 creates a function animal and defines a property on its this: the value of Name,name is the formal parameter when the function is executed.

Line 4th defines a static property on the animal object (the animal itself is a function object): Color, and assigns "black"

Line 5-7 defines a say () method on the prototype object prototype of the animal function, say the method outputs the name value of this.

Line 8th creates a new object by using the the New keyword cat

10-14 rows of Cat objects attempt to access the name and color properties and invoke the Say method.

The 16-20 row Animal object attempts to access the name and color properties and calls the Say method.

2, focus on the analysis

The 8th line of code is the key:

var cat = new Animal ("cat");
When the JS engine executes this code, it does a lot of work internally, using pseudo code to simulate its workflow as follows:

new Animal ("cat") = {

  var obj = {};

  obj.__proto__ = Animal.prototype;

  var result = Animal.call (obj, "cat");

  Return typeof result = = ' obj '? result:obj;
}

(1) Create an empty object obj;

(2) by pointing the __proto__ of obj to the Animal prototype object prototype, the prototype chain of the Obj object is established: Obj->animal.prototype->object.prototype->null

"If you do not understand the JS prototype chain, please read: JS prototype and prototype chain"

(3) Call the animal function in the execution environment of the Obj object and pass the parameter "cat". Equivalent to var result = obj. Animal ("Cat").

When this sentence is finished, obj produces the attribute name and assigns the value to "cat". "About the use of call in JS please read: JS called and apply"

(4) Examine the return value returned in step 3rd, return obj as the new object if there is no return value, or return a non-object value, otherwise the return value will be returned as a new object.

After understanding the operating mechanism of new, we know that cat is actually the return value of process (4), so we have a little more knowledge of cat objects :

The prototype chain of cat is:cat->animal.prototype->object.prototype->null

A new attribute is added to the cat: name

After analyzing the production process of cat, let's look at the output:

Cat.name-> in procedure (3), the Obj object produces the Name property. So Cat.name is the obj.name here.

Cat.color-> Cat will look up its own color first, and find it along the prototype chain without finding it, and in the example above, we just defined the color on the animal object and didn't define it on its prototype chain, so we couldn't find it.

Cat.say-> Cat will find its own say method first, find it along the prototype chain, and in the example above, we define prototype on the animal say, so we find the Say method on the prototype chain.

In addition, the this.name is also accessed in the Say method, where this refers to its caller obj, so the value of obj.name is output.

For animal, it is also an object in itself, so it follows the lookup rules when accessing properties and methods, so:

Animal.color-> "BLACK"

animal.name-> "Animal" , Animal first finds its own name, finds name, note: But this name is not the name we defined, but the property that is built into the function object.

Typically, a function object is generated with the built-in Name property and the function name as an assignment (function object only).

Animal.say-> Animal did not find the say method in its own, will also follow its prototype chain search, saying that Animal prototype chain is what?

Judging from the test results: Animal's prototype chain is this:

Animal->function.prototype->object.prototype->null

So there is no say method defined on animal's prototype chain!

Second, the significance of new existence

After recognizing the new operator, let's go back to the question that we mentioned in the opening paragraph: JS is the object of everything, why do you want to generate objects through new? To understand this problem, we should first make clear the relationship between cat and animal.

With the above analysis, we found that cat inherits some of the attributes in animal, so we can simply understand that animal and cat are inheritance relationships.

Cat, on the other hand, is an object created by new, so is cat really a animal instance object? Let's take a look at how JS defines "instance objects".

A instanceof B

If the expression above is an instance object that True,js thinks A is B, we use this method to judge the cat and animal

Cat instanceof Animal; True

From the implementation of the results look: cat is indeed a animal example, to confirm this result, we have to understand the instanceof of JS rules:

var L = a.__proto__;
var R = B.prototype;
 if (L = = = R) return
true;

Returns true if the __proto__ of a is equivalent to the prototype of B

In the execution process of new (2), Cat's __proto__ points to the animal prototype, so cat and animal conform to the instanceof judgment result. Therefore, we believe that cat is an instance object of animal.

In JavaScript, you can create an instance object of the original object by using new, which inherits the properties and methods of the original object. Therefore, the meaning of new existence is that it implements the inheritance in JavaScript, not just the instantiation of an Object!

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.