Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js NodeJS模块实例_Node.js - Fatal编程技术网

Node.js NodeJS模块实例

Node.js NodeJS模块实例,node.js,Node.js,我有以下代码。我想使用prototype关键字,因为我想调用方法函数而不是类方法,为什么这会给我一个错误?如果我移除了原型,这就行了。如何编写这段代码以便能够使用实例而不是类方法 //app.js var MyTest = require('./MyTest') var myTestInstance = new MyTest() myTestInstance.testFunction(function(reply){ console.log(reply) }) //MyTest.js m

我有以下代码。我想使用prototype关键字,因为我想调用方法函数而不是类方法,为什么这会给我一个错误?如果我移除了原型,这就行了。如何编写这段代码以便能够使用实例而不是类方法

//app.js
var MyTest = require('./MyTest')
var myTestInstance = new MyTest()
myTestInstance.testFunction(function(reply){
   console.log(reply)
})

//MyTest.js
module.exports = function() {

   function MyTest() {}

   MyTest.prototype.testFunction = function(cb) {
      cb('hello')
   }

   return MyTest

}

要使app.js按原样工作,您需要将MyTest.js的内容替换为以下内容:

function MyTest() {}
MyTest.prototype.testFunction = function(cb) {
  cb('hello');
};
module.exports = MyTest;

在app.js中,您需要的是构造函数,而不是工厂函数。

@johnyhk myTestInstance.testFunction(函数(回复){^TypeError:undefined不是Object中的函数。谢谢!这实际上帮助很大。