Deep understanding of javaScript prototype inheritance

Source: Internet
Author: User
The nature of inheritance: Before discussing prototype inheritance of javaScript, let's think about why inheritance? Consider one scenario. If we have two objects, one of which has the same attributes and the other has different attributes. Usually...



Nature of inheritance: Reuse

Before exploring the prototype inheritance of javaScript, consider why inheritance is required?

Consider one scenario. If we have two objects, one of which has the same attributes and the other has different attributes. A good design scheme is to extract the same logic for reuse.

Take xiaoMing liLei as an example. These two students have their own names and will introduce themselves. Abstract As a program object, which can be expressed as follows.

var xiaoMing = {  name : "xiaoMing",  hello : function(){    console.log( 'Hello, my name is '+ this.name + '.');  }}var liLei = {  name : "liLei",  hello : function(){    console.log( 'Hello, my name is '+ this.name  + '.');  }}

Students who have used java may first think of using object-oriented methods to solve this problem. Create a Person class and instantiate the xiaoMing and liLei objects. ES6 also has a concept similar to the class in java: class.

The following uses ES6 syntax and the object-oriented method to reconstruct the above Code.

class Person {  constructor(name){    this.name = name  }  hello(){    console.log(this.name);  }}var xiaoMing = new Person('xiaoMing');var liLei = new Person('liLei');

You can see that the class is used to create an object to achieve the purpose of reuse. The logic is that two or more objects have similar structures and functions. A template can be abstracted and multiple similar objects can be copied according to the template.

Using classes to create objects is like a bicycle manufacturer reusing the same blueprint over and over again to create a large number of bicycles.

Of course, there are more than one solutions to reuse problems. Traditional object-oriented classes are only one of the solutions. In the following example, the main character "prototype inheritance" is introduced, which solves the reuse problem from another perspective.

Prototype principle prototype object

Objects in javaScript are composed of a set of common attributes and prototype attributes.

var o = {  a : 'a',  ...  __proto__: prototypeObj}

A is;Prototype attributesIt refers to _ proto __. This is not part of the specification. Later, chrome exposed the underlying attributes of this language through _ proto _, which was gradually accepted and added to the ES6 specification. The value of o. _ proto _ prototypeObj is alsoPrototype object. The prototype object is actually a common object. It is called a prototype object only because it is the value referred to by the prototype property.

Prototype objects are special because they do not have the ability to share their attributes with other objects.

In the ES6 specification, it is defined as follows:

object that provides shared properties for other objects
Attribute read Operations

Return to the initial example to see how to use prototype inheritance for reuse.

var prototypeObj = {  hello: function(){    console.log( 'Hello, my name is '+ this.name  + '.');  }  // ...}var xiaoMing = {  name : "xiaoMing",  __proto__ : prototypeObj}var liLei = {  name : "liLei",  __proto__ :  prototypeObj}xiaoMing.hello(); // Hello, my name is xiaoMing.liLei.hello();  // Hello, my name is liLei.

The xiaoMing liLei object does not directly have the hello attribute (method), but can read this attribute (execute this method). Why?

Imagine a scenario where you are doing a math job and encounter a difficult problem. You will not do it. You have a good brother who has a lot of mathematics. Ask him and make this question.

There is no hello attribute on the xiaoMing object, but it has a good brother, prototypeObj. Attribute read operation. If the hello attribute is not found on xiaoMing, the system will ask its brother prototypeObj. So the hello method will be executed.

Prototype chain

Or an example of doing a math problem. It is difficult for your brother to answer questions about mathematics. He recommends that you ask another student. In this way, you will not ask again until you have an answer or no one can ask. It seems that there is an invisible chain that brings you and your classmates together.

In JS, the read operation passes through _ proto _ to layer-by-layer link structure, which is called the prototype chain.

var deepPrototypeObj = {  hello: function(){    console.log( 'Hello, my name is '+ this.name  + '.');  }  __proto__ : null}var prototypeObj = {  __proto__ : deepPrototypeObj}var xiaoMing = {  name : "xiaoMing",  __proto__ : prototypeObj}var liLei = {  name : "liLei",  __proto__ :  prototypeObj}xiaoMing.hello(); // Hello, my name is xiaoMing.liLei.hello();  // Hello, my name is liLei.
Implementation of prototype inheritance

In the preceding example, the _ proto _ attribute value is directly modified to implement prototype inheritance. However, in actual production,

Instead, use the Object. create () method.

When you call Object. create (), a new Object is created and the prototype Object of the Object is specified as the first input parameter.

Let's change the example above.

var prototypeObj = {  hello: function(){    console.log( 'Hello, my name is '+ this.name  + '.');  }  // ...}var xiaoMing = Object.create(prototypeObj);var liLei = Object.create(prototypeObj);xiaoMing.name = "xiaoMing";liLei.name = "liLei";xiaoMing.hello(); // Hello, my name is xiaoMing.liLei.hello();  // Hello, my name is liLei.

The author of You-Dont-Know-JS has a very interesting name for the implementation of this prototype inheritance, OLOO (objects-linked-to-other-objects ), this implementation method has the advantage that it does not use any class concept, but only object, so it is very compatible with javaScript features.

Because there is no class in JS, only objects are available.

Unfortunately, there are too many programmers who like classes, so the class concept is added to es6. Next I will talk about the implementation principle of class in JS.

Summary

Class to create objects for reuse. The logic is that two or more objects have similar structures and functions. A template can be abstracted according to the template.CopyMultiple similar objects. Just as bicycle manufacturers reuse the same blueprint over and over again to create a large number of bicycles.

Using prototype inheritance can also achieve reuse. It is based on the logic that two or more objects share a part of the common attributes, which can be abstracted to another independent public object. through special prototype attributes, link A public object with a common object, and use the read (write) Rules to traverse and search for the attributes.Share.

The above is an in-depth understanding of the content inherited by the javaScript prototype. For more information, see the PHP Chinese website (www.php1.cn )!

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.