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
运营商具有非常高的优先权。
- 如何在Node.JS中实现inheritance
- 节点coffeescript类文件和inheritance
- Object.create(BaseObject)和util.inherits(MyObject,BaseObject)有什么区别?
- 如何从基于对象的语言转移到服务器端Node.js JavaScript的大项目?
- 如何在Node.js的模块中使用Object.create进行inheritance
- Node.js,embedded式对象的Mongoose策略模式(inheritance,鉴别器)
- 如何扩展Javascriptdate对象?
- 水线ORM的inheritance
- 如何在node.js中实现jade模板的inheritance