从node 5.0.0版本开始,
util.inherits已经被改变,使用
setPrototypeOf方法支持您所需的行为:
FirstBase.js
function FirstBase(firstBaseProp){
this.firstBaseProp = firstBaseProp;
}
FirstBase.prototype.getFirstBaseProp = function(){
return this.firstBaseProp;
};
module.exports = FirstBase;
SecondBase.js
var FirstBase = require('./FirstBase.js'),
util = require('util');
function SecondBase(firstBaseProp, secondBaseProp){
this.secondBaseProp = secondBaseProp;
SecondBase.super_.apply(this, arguments);
}
SecondBase.prototype.getSecondBaseProp = function(){
return this.secondBaseProp;
};
util.inherits(SecondBase, FirstBase);
module.exports = SecondBase;
ThirdBase.js
var SecondBase = require('./SecondBase.js'),
util = require('util');
function ThirdBase(firstBaseProp, secondBaseProp, thirdBaseProp){
this.thirdBaseProp = thirdBaseProp;
ThirdBase.super_.apply(this, arguments);
}
ThirdBase.prototype.getThirdBase = function(){
return this.thirdBaseProp;
};
util.inherits(ThirdBase, SecondBase);
module.exports = ThirdBase;
instance.js
var ThirdBase = require('./ThirdBase.js');
var instance = new ThirdBase('first', 'second', 'third');
console.log(instance.getFirstBaseProp());
console.log(instance.getSecondBaseProp());
console.log(instance.getThirdBase());
console.log(instance.getFirstBaseProp());
console.log(instance.getSecondBaseProp());
console.log(instance.getThirdBase());
如果你正在运行一个支持setPrototypeOf
的旧版本node(0.12.x支持),你可以直接export
util.inherits并将其用作内部实用函数。