Explanation of javascriptnew's Operating Mechanism _ javascript skills

Source: Internet
Author: User
This article mainly introduces the running mechanism of javascriptnew. For more information, see the new operator in javascript like other advanced languages. We know that the new operator is used to instantiate a class, therefore, an instance object is allocated in the memory. But in javascript, everything is an object. Why do we need to use new to generate objects? This article will take you to explore the new mysteries in javascript...

I. Understanding 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 output above, it means that you already know the new and this running mechanisms in js. Please ignore this article!

We will parse this example to deepen your understanding of the new operator in js! [If you do not know about this in js, read: JS scope and this keyword first]

1. Code Interpretation

In line 1-3, a function Animal is created and its attribute name is defined on this. The value of name is the form parameter when the function is executed.

Row 3 defines a static attribute: color on the Animal object (Animal itself is a function object) and assigns a value of "black"

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

Row 3 creates a new object using the new keyword cat

Line 10-14 cat objects attempt to access the name and color attributes and call the say method.

Lines 16-20 of Animal objects attempt to access the name and color attributes and call the say method.

2. Key Analysis

8th lines of code are critical:

Var cat = new Animal ("cat"); when the JS engine executes this code, it does a lot of work internally. Its workflow is simulated using pseudo code 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) point the _ proto _ of obj to the prototype of the Animal prototype. Then, the prototype chain of the obj object is established: obj-> Animal. prototype-> Object. prototype-> null

[If you do not know about the JS prototype chain, read: JS prototype and prototype chain first]

(3) Call the Animal function in the execution environment of the obj object and pass the "cat" parameter ". It is equivalent to var result = obj. Animal ("cat ").

After this statement is executed, obj generates the attribute name and assigns the value "cat ". [For details about call usage in JS, refer to call and apply in JS]

(4) Evaluate the returned values in step 1. If no value is returned or a non-object value is returned, obj is returned as the new object; otherwise, the return value is returned as the new object.

After understanding the new operating mechanism, we know that cat is actually the return value of Process (4,Therefore, we know more about cat objects.:

The prototype chain of cat is:Cat-> Animal. prototype-> Object. prototype-> null

A new property "name" is added to cat.

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

Cat. name-> in process (3), the obj object generates the name attribute. So cat. name is the obj. name here.

Cat. color-> cat first looks for its own color. If it is not found, it searches along the prototype chain. In the preceding example, we only define color on the Animal object, it is not defined on its prototype chain, so it cannot be found.

Cat. say-> cat first looks for its own say method, and then searches along the prototype chain if it is not found. In the preceding example, we define say on Animal prototype, therefore, the say method is found on the prototype chain.

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

For Animal, it is also an object. Therefore, it also complies with the above Search rules when accessing attributes and methods. Therefore:

Animal. color-> "black"

Animal. name-> "Animal"Animal first searches for its own name and finds the name. Note: however, this name is not the name we define, but the built-in attribute of the function object.

Generally, when a function object is generated, the name attribute is built in and the function name is assigned a value (only the function object ).

Animal. say-> when Animal does not find the say method, it also searches along its prototype chain. What is the prototype chain of Animal?

According to the test results, the prototype chain of Animal is as follows:

Animal-> Function. prototype-> Object. prototype-> null

Therefore, no say method is defined on the prototype chain of Animal!

Ii. Significance of new

After recognizing the new operator, let's go back to the question mentioned at the beginning: In JavaScript, everything is an object. Why do we need to use new to generate objects? To understand this problem, we must first understand the relationship between cat and Animal.

Through the above analysis, we found that cat inherits some attributes of Animal, so we can simply understand that Animal and cat are inherited.

On the other hand, cat is an object generated through new. Is cat An Animal instance object? Let's take a look at how JS defines "instance objects?

A instanceof B

If the above expression is true, JS considers A as the Instance Object of B, we use this method to judge cat and Animal

cat instanceof Animal; //true

According to the execution result, cat is indeed an Animal instance. To verify the result, let's take a look at the Judgment Rules of instanceof in JS:

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

If _ proto _ of A is equivalent to B's prototype, true is returned.

In the new Execution Process (2), cat _ proto _ points to the prototype of Animal, so cat and Animal match the judgment result of instanceof. Therefore, we think that cat is an Animal instance object.

In javascript, a new object can be used to generate an Instance Object of the original object, and this instance object inherits the attributes and methods of the original object. Therefore, the significance of new is that it implements inheritance in javascript, not just instantiating 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.