原型链及组合方式

    1. // Shape - 父类(superclass)
    2. function Shape() {
    3. this.x = 0;
    4. this.y = 0;
    5. }
    6. // 父类的方法
    7. Shape.prototype.move = function(x, y) {
    8. this.x += x;
    9. this.y += y;
    10. console.info('Shape moved.');
    11. };
    12. // Rectangle - 子类(subclass)
    13. function Rectangle() {
    14. Shape.call(this); // call super constructor.
    15. }
    16. // 子类续承父类
    17. Rectangle.prototype = Object.create(Shape.prototype);
    18. Rectangle.prototype.constructor = Rectangle;
    19. var rect = new Rectangle();
    20. console.log('Is rect an instance of Rectangle?',
    21. rect instanceof Rectangle); // true
    22. console.log('Is rect an instance of Shape?',
    23. rect instanceof Shape); // true
    24. rect.move(1, 1); // Outputs, 'Shape moved.'

    如果你希望能继承到多个对象,则可以使用混入的方式。

    1. function MyClass() {
    2. SuperClass.call(this);
    3. OtherSuperClass.call(this);
    4. }
    5. // 继承一个类
    6. MyClass.prototype = Object.create(SuperClass.prototype);
    7. // 混合其它
    8. Object.assign(MyClass.prototype, OtherSuperClass.prototype);
    9. // 重新指定constructor
    10. MyClass.prototype.constructor = MyClass;
    11. MyClass.prototype.myMethod = function() {
    12. // do a thing
    13. };