A detailed explanation of the principles of the Javascript prototype chain and a detailed explanation of the javascript prototype chain

Source: Internet
Author: User
Tags hasownproperty

A detailed explanation of the principles of the Javascript prototype chain and a detailed explanation of the javascript prototype chain

This article analyzes the principles of the Javascript prototype chain. We will share this with you for your reference. The details are as follows:

I. JavaScript prototype chain

ECMAScript describes the concept of prototype chain and uses prototype chain as the main method to implement inheritance. The basic idea is to use the prototype to inherit the attributes and methods of another reference type. In JavaScript, the _ proto _ attribute is used to represent the prototype chain of an object. When you look for an object's properties, JavaScript will traverse the prototype chain up until the property of the given name is found!

For example, the following code is available:

Extension Object class, add Clone and Extend Methods

/* Extension Object class, add Clone, JS method for cloning */Object. prototype. clone = function () {var objClone; if (this. constructor = Object) {objClone = new this. constructor ();} else {objClone = new this. constructor (this. valueOf ();} for (var key in this) {if (objClone [key]! = This [key]) {if (typeof (this [key]) = 'object') {objClone [key] = this [key]. clone ();} else {objClone [key] = this [key] ;}} objClone. toString = this. toString; objClone. valueOf = this. valueOf; return objClone;}/* extends the Object class and adds the Extend method to implement JS inheritance. The target Object will have all the attributes and methods of the source Object */Object. prototype. extend = function (objDestination, objSource) {for (var key in objSource) {if (objSource. hasOwnProperty (key) & objDestination [key] === undefined) {objDestination [key] = objSource [key] ;}} return objDestination ;}

Define the Person class

/* Define a Person class */function Person (_ name, _ age) {this. name = _ name; this. age = _ age ;}

In JavaScript, the Object class is the parent class of all classes. Therefore, the Person class inherits from the Object class and inherits all the public attributes and public methods of the Object class, includes the Clone and Extend methods newly added to the Object class.

The following code proves that the Person class inherits the Object class.

Document. write ("<pre>"); var p = new Person ("lone wolf", 24); // create a Person named lone wolf var cloneP = p. clone (); // p calls the Clone method defined in the Object class to Clone itself. If you can get a cloneP, it proves that the Person class actually inherits the Object class, so we have Clonedocument. writeln ("p is an object created using the Person class as a constructor, p. name = "+ p. name + ", p. age = "+ p. age); document. writeln ("cloneP is the object cloned by calling the Clone method of p, cloneP. name = "+ cloneP. name + ", cloneP. age = "+ cloneP. age); document. writeln ("cloneP objects and p objects are mutually independent objects. The memory addresses of these two objects are definitely not equal. The result of p = cloneP is: "+ (p = cloneP); cloneP. name = ""; // modify the name of cloneP document. writeln ("cloneP name is modified, cloneP. name = "+ cloneP. name); document. writeln ("the name of cloneP is modified, but it does not affect p, p. name = "+ p. name); document. write ("</pre> ");

Running result:

In this case, the Person class inherits the Object class using prototye:

/* Define a Person class */function Person (_ name, _ age) {this. name = _ name; this. age = _ age;} Person. prototype = new Object (); // let the Person class inherit the Object class

As JavaScript requires that any class inherits from the Object class, "Person. prototype = new Object (); // let the Person class inherit the Object class "even if we don't write it, I guess the JavaScript engine will automatically add this sentence for us, or use" Person. prototype = Object. prototype; "This method allows the Person class to inherit the Object class. "Person. prototype = new Object (); ", in fact, this is equivalent to the prototype of the Object as a Person, which is equivalent to copying the attributes and methods of the Object to the Person.

Ii. How the new operator works

Let's take a look at the following code:
Copy codeCode: var p = new Person ("lone wolf", 24); // create a Person named Lone Wolf

A very simple piece of code. Let's see what new has done? We can split the new process into the following three steps:

1. var p ={}; Initialize an object p.

2. p. _ proto __= Person. prototype;, set the property of object p _ proto _ to Person. prototype

3. Person. call (p, "lone wolf", 24); call the constructor Person to initialize p.

The key lies in the second step. Let's prove it:

Var p = new Person ("lone wolf", 24); // create a Person named lone wolf alert ("p. _ proto _ = Person. the result of prototype is: "+ (p. _ proto _ = Person. prototype ));

The running result of Firefox is:

This code returns true. It indicates that step 2 is correct.

Note: __proto _ this attribute is publicly accessible only in firefox or chrome. Therefore, other browsers Based on the IE kernel will not return true.

So what is _ proto? Let's simply put it down here. Each object will Initialize an attribute inside it, namely _ proto __. when we access an object's attribute, if this attribute does not exist inside the object, then he will go to _ proto _ to find this attribute, and this _ proto _ will have his own _ proto __, so he will keep searching like this, that is, the concept of prototype chain.

According to the standard, __proto _ is not made public, that is, it is a private attribute, and the _ proto _ attribute cannot be accessed in IE, however, the Firefox engine exposes it as a public attribute, which can be accessed and configured externally.

Well, the concept is clear. Let's look at the following code:

<script type="text/javascript">    var Person = function () { };    Person.prototype.Say = function () {      alert("Person say");    }    var p = new Person();    p.Say();</script>

This code is very simple. Let's see why p can access the Person's Say.

First
Copy codeThe Code is as follows: var p = new Person ();

We can conclude that
Copy codeThe Code is as follows: p. _ proto __= Person. prototype

So when we call p. when you Say (), p does not have the Say attribute. Therefore, he needs to find it in _ proto _, that is, Person. prototype, and we have defined

Person.prototype.Say=function(){    alert("Person say");};

So we found this method.

Next, let's look at a more complex one.

<Script type = "text/javascript"> var Person = function () {}; Person. prototype. say = function () {alert ("Person say");} Person. prototype. salary = 50000; var Programmer = function () {}; Programmer. prototype = new Person (); // Let the Programmer class inherit Programmer from this class. prototype. writeCode = function () {alert ("programmer writes code") ;}; Programmer. prototype. salary = 500; var p = new Programmer (); p. say (); p. writeCode (); alert (p. salary); </script>

Let's make the following derivation:
Copy codeThe Code is as follows: var p = new Programmer ();

We can conclude that
Copy codeThe Code is as follows: p. _ proto __= Programmer. prototype;

We specify
Copy codeThe Code is as follows: Programmer. prototype = new Person ();

Let's split it like this,

var p1=new Person();Programmer.prototype=p1;

So:

p1.__proto__=Person.prototype;Programmer.prototype.__proto__=Person.prototype;

Obtain
Copy codeThe Code is as follows: p. _ proto __= Programmer. prototype

You can get:
Copy codeThe Code is as follows: p. _ proto _. _ proto __= Person. prototype

Okay. Let's take a look at the above result, p. Say (). Since p does not have the Say attribute. _ proto __, that is, Programmer. prototype, which is found in p1. Since p1 does not have a Say, it goes to p. _ proto __. _ proto __, that is, Person. in prototype, the Say method is found. This is the implementation principle of the prototype chain.

The following code shows how the JS engine looks for attributes:

Function getProperty (obj, prop) {if (obj. hasOwnProperty (prop) return obj [prop]; else if (obj. _ proto __! = Null) return getProperty (obj. _ proto __, prop); // recursive else return undefined ;}

Example: Find the Say method of the p object

<Script type = "text/javascript">/* Find the prop attribute of the obj object */function getProperty (obj, prop) {if (obj. hasOwnProperty (prop) return obj [prop]; else if (obj. _ proto __! = Null) return getProperty (obj. _ proto __, prop); // recursive else return undefined;} var Person = function () {}; // defines the Person class Person. prototype. say = function () {alert ("Person say");} Person. prototype. salary = 50000; var Programmer = function () {}; // defines the Programmer class // Programmer. prototype = new Person (); // Let the Programmer class inherit from the class, write a Programmer. prototype = Person. prototype; // Let the Programmer class inherit from the class, write 2 Programmer. prototype. writeCode = function () {alert ("programmer writes code") ;}; Programmer. prototype. salary = 500; var p = new Programmer (); var SayFn = getProperty (p, "Say"); // find the Say method SayFn of the p object. call (p); // call the found Say method </script>

Running results under Firefox:

Prototype is just an illusion. It only plays an auxiliary role in implementing the prototype chain. In other words, prototype only has some value when it is new, and the essence of prototype chain is, in fact, it is _ proto __.

I hope this article will help you design JavaScript programs.

Articles you may be interested in:
  • Ultimate explanation of JavaScript prototype and prototype chain
  • Javascript prototype chain and inheritance
  • Understanding the javaScript prototype chain
  • Explanation of the original JavaScript model and prototype chain
  • Prototype chain inheritance instance of js Object Inheritance
  • Javascript prototype chain maintenance and inheritance
  • A misunderstanding of Javascript prototype chain and prototype
  • Javascript learning notes (5) prototype and prototype chain
  • Deep understanding of prototype chain in javascript
  • Incomplete inheritance of javascript tutorials (js prototype chain)

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.