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
运营商具有非常高的优先权。
- Javascript可写描述符是否阻止实例的更改?
- 为什么console.log()不显示Object.create的inheritance属性?
- Nodejs + expressjs中的类成员inheritance
- 理解javascriptinheritance和node.js utilinheritance函数的例子
- `util.inherits`和在NodeJS中扩展原型的区别
- 如何在NodeJS中为自定义错误类获取正确的回溯?
- 使用Node.js,Handlebars和Express进行模板inheritance
- Node.JS中的inheritance
- JavaScriptinheritance框架