Home > Web Front-end > JS Tutorial > A detailed explanation of the inheritance mechanism in js

A detailed explanation of the inheritance mechanism in js

阿神
Release: 2017-10-24 09:16:25
Original
1484 people have browsed it

Preface

I have been learning vue recently, and I finally have time to write something on the weekend (I am a little excited when I think about being able to deceive likes again!). In the basics of JavaScript, in addition to closures, inheritance is also a difficulty. Because of the length of the article, I plan to divide it into two parts. Also based on "Javascript Advanced Programming", I will give a detailed explanation. If there is anything wrong, please correct me.

Preparatory knowledge

In order to better explain inheritance, let’s put some preparatory knowledge first.

1. Constructor, instance

Constructor is a function used to create objects, and is essentially a function. The difference from other functions is that the calling method is different:

  • If it is called through the new operator, it is the constructor

  • If it is not called through the new operator, it is an ordinary function
    Example:

function Person(name, age) {
   this.name = name;
   this.age = age;
 }
 //当做构造函数调用
 var person1 = new Person('Mike',10);
 
 //当做普通函数调用,这里相当于给window对象添加了name和age属性,这个不是重点,只要注意调用方式
 Person('Bob',12);
 
 console.log(person1)//Person {name: "Mike", age: 10}
 console.log(name)//Bob
 console.log(age)//12
Copy after login

in var person1 = new Person('Mike',10);, the function Person is called through the new operator, and person1 is generated. The Person here is Called the
constructor , person1 is called a instance of the Person function object. There will be a constructor attribute in the instance, pointing to the corresponding constructor , see the following example:

 function Person(name, age) {
    this.name = name;
    this.age = age;
  }
 var person1 = new Person('Mike',10);
 var person2 = new Person('Alice',20);
 console.log(person1.constructor)//function Person(){省略内容...}
 console.log(person2.constructor)//function Person(){省略内容...}
Copy after login

2. Prototype object

When we Every time a function is created, the function object will have a

prototype attribute, which is a pointer that points to its prototype object. The essence of the prototype object is also an object. This sentence may be a bit difficult to understand when you first read it. For example, take the function just now:

function Person(name, age) {
        this.name = name;
        this.age = age;
     }
     console.log(Person.prototype)//object{constructor:Person}
Copy after login

You can see that

Person.prototype points to an object, which is the prototype of Person Object , and this object has a constructor attribute, which points to the Person function object. Feeling a little dizzy? It doesn't matter, next we will use a better method than giving examples-drawing pictures.

3. The relationship between constructor, prototype object and instance

In front, we have just introduced the constructor, instance and prototype object. Next, we use a picture to represent these three (It’s really troublesome to draw this kind of picture with PS. If you have any good tools to recommend):


A detailed explanation of the inheritance mechanism in js From the picture we can see:

  • The

    prototype of the function object points to the prototype object, and the constructor of the prototype object points to the of the instance object

  • of the function object The [Protoptype] attribute points to the prototype object . The [Protoptype] here is the internal property . It can be understood that it exists, but it is not allowed. When we access (although some browsers allow access to this attribute, let's understand it this way first), the function of this attribute is: Allow the instance to access the properties and methods in the prototype object through this attribute. For example:

  • function Person(name, age) {
            this.name = name;
            this.age = age;
          }
          //在原型对象中添加属性或者方法
         Person.prototype.sex = '男'; 
         var person1 = new Person('Mike',10);
         var person2 = new Person('Alice',20);
         //只给person2设置性别
         person2.sex = '女';
         console.log(person1.sex)//'男'
         console.log(person2.sex)//'女'
    Copy after login
Here we do not set the

sex attribute for the person1 instance, but because of [Protoptype] exists, the corresponding attribute in the prototype object will be accessed; At the same time, after we set the
sex attribute to person2, the output is 'female', indicating that only when the instance itself does not have the corresponding attribute or method Only then will we find the corresponding properties or methods on the prototype object

Inheritance

Prototype chain

In js, the main idea of ​​inheritance is to use the prototype chain , so if you understand the prototype chain, the inheritance problem is half understood. You can take a short break here. If you have almost understood the previous preparatory knowledge, you can start talking about the prototype chain.

The principle of the prototype chain is to let one reference type inherit the properties and methods of another reference type. Let’s review the knowledge just mentioned:

  • Prototype object points to the constructor through the constructor attribute

  • InstancePoints to the prototype object through the [Prototype] attribute

Now let’s think about a question:

What happens if the prototype object is equal to an instance of another constructor? For example:

    function A() {
     
    }
    //在A的原型上绑定sayA()方法
    A.prototype.sayA = function(){
            console.log("from A")
    }
    function B(){

    }
    
     //让B的原型对象指向A的一个实例
     B.prototype = new A();
     
     //在B的原型上绑定sayB()方法
     B.prototype.sayB = function(){
            console.log("from B")
     }
     //生成一个B的实例
     var a1 = new A();
     var b1 = new B();
     
     //b1可以调用sayB和sayA
     b1.sayB();//'from B'
     b1.sayA();//'from A'
Copy after login
In order to easily understand what just happened, let’s take another picture:


A detailed explanation of the inheritance mechanism in jsNow look at the code combined with the picture:

  • First, we created two function objects A and B,

    and also generated their prototype objects

  • Next, we added the sayA() method
    * to the prototype object of A, and then the critical step B.prototype = new A() ;, we let the protytype pointer of function object B point to an instance of A, please pay attention to my description: let the of function object B The protytype pointer points to an instance of A, which is why in the end, B's prototype object no longer has a constructor attribute. In fact, B originally had a real prototype object, which could have been passed B.prototype access, but we have now rewritten this pointer so that it points to another object, so the real prototype object of B cannot be accessed now. Instead, the new prototype object is an instance of A, so naturally there is no constructorAttribute

  • Next we add a sayB method# to the object pointed to by B.prototype

  • ##Then, we generated an instance b1

  • Finally, we called the sayB method of b1, which can be executed. Why?


    Because b1 has a [Prototype] property that can access the methods in B prototype;

  • We called the sayA method of b1, Can be executed, why?


    Because b1 can access B prototype along the [Prototype] property, B prototype continues to access A prototype along the [Prototype] property, and finally on A.prototype The sayA() method is found, so it can be executed

So, the current result is equivalent to,

b1 inherits the properties and methods of A, this A structure that [Prototype] continuously connects instances and prototype objects is the prototype chain. It is also the main implementation method of inheritance in js. Original text from https://segmentfault.com/a/1190000007376061

The above is the detailed content of A detailed explanation of the inheritance mechanism in js. For more information, please follow other related articles on the PHP Chinese website!

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