ES5的继承

116 阅读1分钟

ES5 的继承

MDN使用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;

var 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.'
// 子类续承父类 合并为一句
Rectangle.prototype = Object.create(Shape.prototype,{
  constructor:{value:Rectangle}
});


但是ES6 中的静态属性 可以被子类继承

class Shape {
    constructor() {
    }
}
Shape.s = 10
class Rectangle extends Shape {
  constructor() {
    super()
  }
}
console.log(Rectangle.s) // 10


所以需要把静态属性遍历后挂到子类身上

for (let [key, value] of Object.entries(Shape)) {
  Rectangle[key] = value
}


总结核心

// Shape - 父类(superclass)
function Shape() {
}

// 父类的方法
Shape.prototype.move = function() {
};

///////////////////////////////////////////////////////////////    1 子类中call修改this指向
// Rectangle - 子类(subclass)
function Rectangle() {
  Shape.call(this); // call super constructor.
}

///////////////////////////////////////////////////////////////    2 子类添加 prototype
// 子类续承父类 合并为一句
Rectangle.prototype = Object.create(Shape.prototype,{
  constructor:{value:Rectangle}
});

///////////////////////////////////////////////////////////////    3 遍历静态属性挂到子类身上 
for (let [key, value] of Object.entries(Shape)) {
  Rectangle[key] = value
}