有關javascript的繼承在《javascript 高級程序設計》第三版 中講的很詳細,也極力推薦初學者學習本書。
javascript
function object(o) { function F(){} F.prototype = o; return new F(); } function inherit(subType,superType) { var p = object(superType.prototype); p.constructor = subType; subType.prototype = p; } function Super(name) { this.name = name; this.colors = ['red','blue']; } Super.prototype.getName = function() { console.log('This is name ' + this.name); } function Sub (name ,age) { Super.call (this,name); this.age = age; } inherit(Sub,Super);//Node.js的高階函數繼承使用的這種方式 Sub.prototype.getAge = function() { console.log('This is age ' + this.age ); } var inst = new Sub('Hello,world',20); inst.colors.push('white'); console.log(inst.colors); inst.getName(); inst.getAge(); var inst1 = new Sub('Hi,god',30); inst1.colors.push('yellow'); console.log(inst1.colors); inst1.getName(); inst1.getAge();