Thoroughly get to know the prototype and __proto__

prototype is a function-specific property is a static property Function; __ proto__ object-specific attributes.

Because the function itself is an object, so the function of both prototype property also has __proto__ property.

When using the function prototype property, it is used as a constructor;

When the function is used __proto__ property, it is used as an object.

In addition, __ proto__ Property Internal Property, try not to use. May be replaced with setPrototypeOf () and getPrototypeOf ().

1) are ordinary function values

    function C () {} 
    the console.log (C.prototype); 
    / * {constructor: function C () {}, __ proto__: Object} * / 
    // use the __proto__, ordinary function object, the prototype object point Funtion prototype property 
    console.log (C .__ proto__ === Function.prototype) ;

For the ordinary function is, prototype __proto__ properties and attributes are read-write property.

Assigned to the prototype, and will change the prototype object above the constructor function.

    function C() {}
    function D() {}
    C.prototype = new D();
    console.log(Object.getOwnPropertyDescriptor(C, 'prototype'));
    /*
    {value: D, writable: true, enumerable: false, configurable: false} //可写
    */
    console.log(C.prototype.constructor === D); // true

2) class category values, respectively, and a normal function

  class A{}
  console.log(A.prototype);
  // {constructor: ƒ, __proto__: Object}
  console.log(A.__proto__ === Function.prototype);// true

However, in the class, prototype property is read-only

  class A{}
  class B{
    add(){console.log('add')}
    static add(){console.log('static add')}
  }
  const a = new A();
  const b= new B();
  console.log(Object.getOwnPropertyDescriptor(A, 'prototype'));
  // {value: {…}, writable: false, enumerable: false, configurable: false}; // 只读
  A.__proto__ = B; // 静态属性方法继承
  b.add(); // add
  // a.add(); ❌ 不存在
  A.add(); // static add
  A.prototype.__proto__ = B.prototype; // Examples Properties Methods inherited 
  a.add (); // the Add

 

Guess you like

Origin www.cnblogs.com/lyraLee/p/11617712.html