通过一个例子程序来感受构造函数的继承

有一构造函数如下:

 1 function Shape() {
 2   this.x = 0;
 3   this.y = 0;
 4 }
 5 
 6 Shape.prototype.move = function (x, y) {
 7   this.x += x;
 8   this.y += y;
 9   console.info('Shape moved.');
10 };

使用构造函数的主要目的就是创建实例对象,构造函数内部的this所关联的也是实例对象。

另一个构造函数继承上述构造函数:

 1 // 第一步,子类继承父类的实例
 2 function Rectangle() {
 3   Shape.call(this); // 调用父类构造函数
 4 }
 5 // 另一种写法
 6 function Rectangle() {
 7   this.base = Shape;
 8   this.base();
 9 }
10 
11 // 第二步,子类继承父类的原型
12 Rectangle.prototype = Object.create(Shape.prototype);
13 Rectangle.prototype.constructor = Rectangle;
原文地址:https://www.cnblogs.com/flyover/p/14319155.html