Node.js模块的inheritance

我在node.js中有inheritance问题 我遵循从现有的线程stackoverflow模式,但我的代码仍然不能像它应该。

让我们从两个项目开始,第一个'base.js':

function Base() { this.type = 'empty'; } Base.prototype.getType = function () { return this.type; } module.exports = Base; 

然后我有我的“second.js”文件,它应该inheritance基地

 var Base = require('./base.js'), util = require('util'); function Second() { Base.apply(this, arguments); } util.inherits(Second, Base); Second.prototype.getData = function () { return 12; } module.exports = Second; 

在我的app.js中我打电话

 var second = new require('./second.js'); console.log(second.getType()); 

这就是抛出错误“getType是未定义的”。 但是,当我把所有这一切在一个单一的文件(例如app.js),这一切工作正常。 你能指出我的代码有什么问题,或者提出一个更好的方法吗?

谢谢!

在你的app.js中,你需要首先需要构造函数,然后构造新的实例:

 var Second = require('./second.js'); var second = new Second(); console.log(second.getType()); 

或者你也可以这样做:

 var second = new (require('./second.js')); console.log(second.getType()); 

但无论如何,您只需申请new运营商即可。 它与运营商优先权有关 , new运营商具有非常高的优先权。