简体   繁体   English

如何从Node.js中的另一个文件正确创建原型对象?

[英]How do I properly create prototype objects from another file in Node.js?

I'm running into a really frustrating problem in Node.js. 我在Node.js中遇到了一个非常令人沮丧的问题。

I'll start with what I'm doing. 我将从我正在做的事情开始。

I'm creating an object in a file and then exporting the constructor and creating it in other files. 我正在文件中创建一个对象,然后导出构造函数并在其他文件中创建它。

My objects are defined like so: 我的对象定义如下:

File 1: 文件1:

var Parent = function() {};

Parent.prototype = {
     C: function () { ... }
}

module.exports = Parent;

File 2: 档案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;

I'm trying to use the object like so in another file 我正在尝试在另一个文件中使用对象

File 3: 文件3:

var Obj = require('../obj.js'),
      obj = new Obj();

obj.A(); 

I receive the error: 我收到错误:

TypeError: Object [object Object] has no method 'A'

however when I run Object.getPrototypeOf(obj) I get: 但是,当我运行Object.getPrototypeOf(obj)时,我得到:

{ A: [Function], B: [Function] }

I have no idea what I'm doing wrong here, any help would be appreciated. 我不知道我在做什么错,任何帮助将不胜感激。

I cannot reproduce your problem. 我无法重现您的问题。 Here is my setup: 这是我的设置:

parent.js parent.js

var Parent = function() {};

Parent.prototype = {
  C: function() {
    console.log('Parent#C');
  }
};

module.exports = Parent;

child.js 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 main.js

var Child = require('./child');
child = new Child();

child.A();
child.C();

And running main.js : 并运行main.js

$ node main.js
Child#A
Parent#C

The source code is clonable via Git at the following Gist: https://gist.github.com/4704412 源代码可通过以下Gist上的Git克隆: https : //gist.github.com/4704412


Aside: to clarify the exports vs module.exports discussion: 旁白:澄清exports VS module.exports讨论:

If you want to attach new properties to the exports object, you can use exports . 如果要将新属性附加到导出对象,则可以使用exports If you want to completely reassign exports to a new value , you muse use module.exports . 如果要完全将导出重新分配为新值 ,请使用module.exports For example: 例如:

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM