这是一个开箱即用的示例。如果您想减少“ hacky”,则应使用继承库或类似的库。
在文件animal.js中,您应该编写:
var method = Animal.prototype;function Animal(age) { this._age = age;}method.getAge = function() { return this._age;};module.exports = Animal;要在其他文件中使用它:
var Animal = require("./animal.js");var john = new Animal(3);如果要“子类”,请在mouse.js中:
var _super = require("./animal.js").prototype, method = Mouse.prototype = Object.create( _super );method.constructor = Mouse;function Mouse() { _super.constructor.apply( this, arguments );}//Pointless override to show super calls//note that for performance (e.g. inlining the below is impossible)//you should do//method.$getAge = _super.getAge;//and then use this.$getAge() instead of super()method.getAge = function() { return _super.getAge.call(this);};module.exports = Mouse;您也可以考虑“方法借用”而不是垂直继承。您无需从“类”继承即可在其类上使用其方法。例如:
var method = List.prototype; function List() { } method.add = Array.prototype.push; ... var a = new List(); a.add(3); console.log(a[0]) //3;


