2

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] }

ここで何が間違っているのかわかりません。助けていただければ幸いです。

4

1 に答える 1

5

私はあなたの問題を再現することはできません。これが私の設定です:

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対のmodule.exports議論を明確にするために:

exportsオブジェクトに新しいプロパティをアタッチする場合は、を使用できますexportsエクスポートを新しい値に完全に再割り当てする場合は、useを使用しますmodule.exports。例えば:

// correct
exports.myFunc = function() { ... };
// also correct
module.exports.myFunc = function() { ... };

// not correct
exports = function() { ... };
// correct
module.exports = function() { ... };
于 2013-02-04T00:42:29.073 に答える