0
点赞
收藏
分享

微信扫一扫

#yyds干货盘点#用Object.create实现类式继承

1.代码

/**
* 用 Object.create实现类式继承
* **/
// Shape - 父类(superclass)
function Shape() {
this.x = 0;
this.y = 0;
}

// 父类的方法
Shape.prototype.move = function (x, y) {
this.x += x;
this.y += y;
console.info('Shape moved.');
};

// Rectangle - 子类(subclass)
function Rectangle() {
Shape.call(this); // call super constructor.
}

// 子类续承父类
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

const rect = new Rectangle();

console.log('Is rect an instance of Rectangle?',
rect instanceof Rectangle); // true
console.log('Is rect an instance of Shape?',
rect instanceof Shape); // true
rect.move(1, 1); // Outputs, 'Shape moved.'

2.核心代码说明

#yyds干货盘点#用Object.create实现类式继承_构造函数

实例对象rect可以访问构造函数Rectangle的prototype,

构造函数Rectangle的prototype又继承于Shape.prototype

也就是,中途有两道继承

所以,我们可以得出

rect.__proto__.__proto__ 与 Shape.prototype 是相等的

console.log('是否相等', rect.__proto__.__proto__ === Shape.prototype) // 输出结果为 true


举报

相关推荐

0 条评论