Understand the inheritance method of JavaScript

Preface

In JavaScript, we can simulate inheritance by manipulating prototype objects.
Before learning inheritance, we need to understand the prototype objects in the following JavaScript.


1. The difference between __prto__ and prototype

Objects having _proto_properties, it may be referred to as "hidden prototyping" . The implicit prototype of an object points to the prototype of the constructor function that constructed the object, which also ensures that the instance can access the properties and methods defined in the constructor function prototype.
The method of this particular subject, in addition to having the above _proto_properties, prototypethe properties unique to the method.
When we create an instance of an object, object _proto_attribute points to the default function prototypeattributes.

    function Person(name){
    
    
        this.name = name;
        this.sayName = function(){
    
    
            console.log(`我叫${
      
      this.name}`)
        }
    }
    var person1 = new test();//生成对象person1实例化Test构造方法
    var person2 = new test();
    /*
        对象t生成时会从Object继承一个__proto__属性,指向创造它的构造方法原型-->构造方法test。
    */
    t.__proto__ === test.prototype;// true 

Code operation mechanism:

  1. After creating a custom constructor, its prototype object will only have contructor properties by default , and other properties and methods are inherited from Object.

The constructor property returns the body of the function that created this object.

  1. When the constructor is called to create a new instance, the inside of the instance will contain a pointer to the prototype object of the constructor. ECMA5 calls this pointer [[prototype]] . Although there is no standard way of accessing [[prototype]] in scripts , Firefox, Safari, and Chrome support an attribute __proto__ on each object. In IE browser, this attribute is completely invisible. But the real point to be clear is that this connection exists between the instance object and the prototype object of the constructor ( that is, the constructor name.prototype ), not between the instance and the constructor.
    Image text

Inheritance in JS


Use prototype to add data to the prototype array

reference

知乎: [[https://zhuanlan.zhihu.com/p/92894937]]
CSDN:[[https://blog.csdn.net/q5706503/article/details/82947977]]

Guess you like

Origin blog.csdn.net/qq_35370002/article/details/107903014