Home > Web Front-end > JS Tutorial > body text

Deep understanding of javaScript prototypal inheritance

黄舟
Release: 2017-02-21 11:19:19
Original
898 people have browsed it



#The essence of inheritance: reuse

Before discussing prototypal inheritance in javaScript, you might as well think about why we need inheritance?

Consider a scenario, if we have two objects, some of them have the same properties, and the other has different properties. Usually a good design solution is to extract the same logic for reuse.

Take two classmates xiaoMing liLei as an example. The two classmates have their own names and will introduce themselves. Abstracted as a program object, it can be represented 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  + '.');
  }
}
Copy after login

Students who have used Java may first think of using object-oriented to solve this problem. Create a Person class and instantiate two objects, xiaoMing and liLei. In ES6, there is also a concept similar to classes in Java: class .

The following uses ES6 syntax and uses object-oriented ideas 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');
Copy after login

You can see that using classes to create objects achieves the purpose of reuse. The logic it is based on is that if 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 blueprints over and over again to build a large number of bicycles.

Of course there is more than one solution to the reuse problem. Traditional object-oriented classes are just one of the solutions. Now it is the turn of our protagonist "prototypal inheritance" to appear, which solves the problem of reuse from another angle.

Principle of prototypal inheritance

Prototype object

Object in javaScript consists of two parts, a collection of ordinary properties, and prototype properties.

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

Ordinary attributes refer to a; Prototype attributes refer to __proto__. This was not part of the specification. Later, chrome exposed the underlying properties of the language through __proto__, which was gradually accepted by everyone and was added to the ES6 specification. The value of o.__proto__ prototypeObj is Prototype Object. The prototype object is actually an ordinary object. The reason why it is called a prototype object is just because it is the value pointed by the prototype attribute.

The prototype object is special because it has an ability that ordinary objects do not have: sharing its properties with other objects.

In the ES6 specification, it is defined as follows:

object that provides shared properties for other objects
Copy after login

Attribute read operation

Go back to the original example and see how to use prototypal inheritance to achieve reuse Purpose.

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.
Copy after login

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

Imagine a scenario where you are doing math homework and encounter a difficult question that you cannot do. And you have a good brother who is very good at mathematics. You go to ask him for help and solve this problem.

There is no hello attribute on the xiaoMing object, but it has a good brother, prototypeObj. For attribute reading operations, if the hello attribute is not found on xiaoMing, it will ask its brother prototypeObj. So the hello method will be executed.

Prototype chain

It’s still an example of doing math problems. Your math question is difficult and your brother doesn't have the answer. He recommends that you ask another classmate. That way you won't ask anymore until you have the answer or there's no one left to ask. It's like there is an invisible chain linking you with your classmates.

In JS, the read operation will be chained layer by layer through __proto__, 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.
Copy after login

Implementation of prototypal inheritance

In the above example, prototypal inheritance is implemented by directly modifying the __proto__ attribute value. But in actual production,

The alternative is to use the Object.create() method.

Calling the Object.create() method will create a new object and specify the prototype object of the object as the first parameter passed in.

Let’s change the above example.

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.
Copy after login

The author of You-Dont-Know-JS gave the implementation of this prototype inheritance a very interesting name OLOO (objects-linked-to-other-objects). The advantages of this implementation It does not use the concept of any class, only object, so it is very consistent with the characteristics of JavaScript.

Because there are no classes in JS, only object.

Unfortunately, there are too many programmers who like classes, so the class concept was added in ES6. The next article will talk about the implementation principle of class in JS

Summary

Class creates objects to achieve the purpose of reuse. The logic it is based on is that two or more objects have similar structures and functions, and a template can be abstracted, and multiple similar objects can be copied according to the template. It's like bike manufacturers reusing the same blueprints over and over again to build lots of bikes.

Using prototypal inheritance can also achieve the purpose of reuse. The logic it is based on is that two or more objects have some shared attributes. The shared attributes can be abstracted to another independent public object. Through special prototype attributes, the public objects and ordinary objects can be linked and reused. Attribute reading (writing) rules are traversed and searched to realize attribute sharing.

The above is an in-depth understanding of javaScript prototypal inheritance. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template