原型链及组合方式
// 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); // trueconsole.log('Is rect an instance of Shape?',rect instanceof Shape); // truerect.move(1, 1); // Outputs, 'Shape moved.'
如果你希望能继承到多个对象,则可以使用混入的方式。
function MyClass() {SuperClass.call(this);OtherSuperClass.call(this);}// 继承一个类MyClass.prototype = Object.create(SuperClass.prototype);// 混合其它Object.assign(MyClass.prototype, OtherSuperClass.prototype);// 重新指定constructorMyClass.prototype.constructor = MyClass;MyClass.prototype.myMethod = function() {// do a thing};
