Implementation class type inherited by Object.create

Object.create

The official document: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/create




Object.create()Method creates a new object, use an existing object as the object of the newly created __proto__.

const person = {
  isHuman: true,
  hello: function () {
    console.log('hello!');
  }
};

const me = Object.create(person);

Now the object pointed to me the prototype object person:

me.__proto__ === person
// true

me.isHuman
// true

me.hello()
// hello!




Implementation class type inherited by Object.create

// 父类
function Shape() {};

// 父类方法
Shape.prototype.duplicate = function() {
  console.log('duplicate')
};

// 子类
function Circle(radius) {
  this.radius = radius;
};

// Circle 继承 Shape
Circle.prototype = Object.create(Shape.prototype);

// 子类的方法
Circle.prototype.draw = function() {
  console.log('draw');
};

Circle now generated by the object constructor c have the attributes and methods of its parent class Shape:

let c = new Circle(1);

c.duplicate()
// duplicate

Explain:

c.__proto__ === Circle.prototype
// true

C examples of __proto__constructors point c of Circlethe prototype, it was no problem.

So Circle.prototypeof __proto__what is now pointing to it?

We declare Circle.prototype = Object.create(Shape.prototype); it Circle.prototype's __proto__pointing Shape.prototype.

Circle.prototype.__proto__ === Shape.prototype
// true

Prototype prototype points to all instances of the c Shape.prototype:

c.__proto__.__proto__ === Shape.prototype
// true

This is the inheritance principle.

Guess you like

Origin blog.csdn.net/weixin_33778544/article/details/90801857