[英]How do I properly create prototype objects from another file in Node.js?
我在Node.js中遇到了一個非常令人沮喪的問題。
我將從我正在做的事情開始。
我正在文件中創建一個對象,然后導出構造函數並在其他文件中創建它。
我的對象定義如下:
文件1:
var Parent = function() {};
Parent.prototype = {
C: function () { ... }
}
module.exports = Parent;
檔案2:
var Parent = require('foo.js'),
util = require('util'),
Obj = function(){ this.bar = 'bar' };
util.inherits(Obj, Parent);
Obj.prototype.A = function(){ ... };
Obj.prototype.B = function(){ ... };
module.exports = Obj;
我正在嘗試在另一個文件中使用對象
文件3:
var Obj = require('../obj.js'),
obj = new Obj();
obj.A();
我收到錯誤:
TypeError: Object [object Object] has no method 'A'
但是,當我運行Object.getPrototypeOf(obj)時,我得到:
{ A: [Function], B: [Function] }
我不知道我在做什么錯,任何幫助將不勝感激。
我無法重現您的問題。 這是我的設置:
parent.js
var Parent = function() {};
Parent.prototype = {
C: function() {
console.log('Parent#C');
}
};
module.exports = Parent;
child.js
var Parent = require('./parent'),
util = require('util');
var Child = function() {
this.child = 'child';
};
util.inherits(Child, Parent);
Child.prototype.A = function() {
console.log('Child#A');
};
module.exports = Child;
main.js
var Child = require('./child');
child = new Child();
child.A();
child.C();
並運行main.js
:
$ node main.js
Child#A
Parent#C
源代碼可通過以下Gist上的Git克隆: https : //gist.github.com/4704412
旁白:澄清exports
VS module.exports
討論:
如果要將新屬性附加到導出對象,則可以使用exports
。 如果要完全將導出重新分配為新值 ,請使用module.exports
。 例如:
// correct
exports.myFunc = function() { ... };
// also correct
module.exports.myFunc = function() { ... };
// not correct
exports = function() { ... };
// correct
module.exports = function() { ... };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.