错过原型function的时候“新”一个实例

我在nodejs中写了一个模块,Test.js,代码打击

function Test() { this.key = 'value'; } Test.prototype.foo = function () { return 'foo'; } module.exports = Test; 

然后在B.js

 var Test = require('./services/Test'); var test = new Test(); console.log(test.foo()); 

不幸的是,我得到了“未定义的方法富”,任何人谁可以告诉我什么事情? 非常感谢

我创建一个Express示例项目,你可以看到代码,仍然无法获得“原型”

检查你的文件位置应该在服务目录中。

 function Test() { this.key = 'value'; } Test.prototype.foo = function () { return 'foo'; } module.exports = new Test();//Test; var test = require('./services/Test'); console.log(test.foo()); 

您可以导出Test类的新对象。 尝试这个。 或者你可以使用ES6的JavaScript很棒。

Test.js中,尝试将module.exports移动到定义原型函数之前。

如下:

 function Test() { this.key = 'value'; } module.exports = Test; Test.prototype.foo = function () { return 'foo'; }