JS中繼承方式的實現有多種方法,下面是比較推薦的方法,其它繼承方式可作了解:javascript
function object(o) { function F() {} F.prototype = o; return new F(); } function inheritPrototype(subType, superType) { var newObj = object(superType.prototype); newObj.constructor = subType; subType.prototype = newObj; } function People() { this.cls = 'people'; } People.prototype.say = function(name) { name = name || this.cls; console.log('My class is '+ name); } function Student() { People.call(this); this.type = 'student'; } inheritPrototype(Student, People); Student.prototype.goToSchool = function() { console.log('I go to school every day.'); } // 測試 var stu = new Student(); console.log('class: ' + stu.cls); // class: people console.log('type: ' + stu.type); // type: student stu.say(); // My class is people stu.goToSchool (); // I go to school every day.
其實,javascript 已經提供了更簡單的實現方法,不必在這造輪子,並且方法不完善,MDN 例子:java
// 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.'
若是你但願能繼承到多個對象,則能夠使用混入的方式:segmentfault
function MyClass() { SuperClass.call(this); OtherSuperClass.call(this); } // 繼承一個類 MyClass.prototype = Object.create(SuperClass.prototype); // 混合其它 Object.assign(MyClass.prototype, OtherSuperClass.prototype); // 從新指定constructor MyClass.prototype.constructor = MyClass; MyClass.prototype.myMethod = function() { // do a thing };