我刚刚接触 NodeJS 一点点,在尝试为其创建一个(非常)基本的 MVC 实现时遇到了障碍。
归结为以下几点。我有一个 Controller 的主要对象,我正在尝试为其创建原型(prototype);代码如下:
var Controller = function(obj) {
this.request = null;
this.response = null;
this.params = null;
this.layout = 'default';
}
Controller.prototype = new function() {
this.processAction = function(action) {
console.log("Processing Action.");
}
}
module.exports = new Controller();
我已经删除了这个问题的大部分值/函数,因为它们并不真正相关。基本上根据我的理解,使用 module.exports 将使用 require() 函数将对象导出到变量。我的调度程序中有以下内容:
var Controller = require('./Controller.js');
问题是每当我打印变量 Controller 时,我都会得到对象的第一部分,但原型(prototype)尚未包含在内。请参阅以下打印输出:
{ request: null,
response: null,
params: null,
layout: 'default' }
因此调用原型(prototype)函数Controller.processAction()会导致无方法错误。我是否声明此原型(prototype)是错误的,或者我是否遗漏了与 NodeJS 相关的内容?
[编辑]
我也尝试过以下样式来添加原型(prototype),但没有成功。
Controller.prototype = {
'processAction' : function(action) {
console.log("Processing Action");
}
}
[编辑2]
没关系,上面的 console.log 没有报告原型(prototype)中的附加功能,有趣。
最佳答案
Controller.prototype = {
processAction : function(){
// code
},
anotherMethod : function(){
}
}
关于javascript - NodeJS Module.Exports 对象原型(prototype)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6447183/