我正在我的Node应用程序中构建一个Controller
函数。无论出于何种原因,this
不是我认为的原型方法。我假设(可能是错误的)this
将是Controller
的一个实例。我在这里做错了什么?
var Controller = function(db) {
var Model = require('../models/activities.js');
this.model = new Model(db);
this.async = require('async');
};
Controller.prototype.getStory = function (activity, callback) {
console.log(this.model); // undefined
};
module.exports = Controller;
答案 0 :(得分:4)
您永远不会在您显示的代码中构建Controller
的实例。
module.exports = Controller;
将构造函数传递给客户端模块,但要构建一个实例,您必须执行
module.exports = new Controller;
或者,如果您希望其他模块使用导出创建Controller
,则必须使用new
运算符。
答案 1 :(得分:1)
我建议您阅读this article以了解JavaScript中与this
相关的所有内容。我假设您碰到了以下问题(我无法确定,因为您没有提供调用getStory
的代码):
var c = new Controller();
// simple example
var f = c.getStory;
f(); // this.model will probably be undefined
// further examples (easy to bump into when working with Node.js callbacks)
setTimeout(c.getStory, 100);
fs.readFile("/etc/passwd", c.getStory);
由于您使用的是Node.js,因此可以依赖Function.prototype.bind
存在(锁定this
引用)。
fs.readFile("/etc/passwd", c.getStory.bind(c)) // should work
答案 2 :(得分:0)
问题在于您的第一行代码:
var Controller = function(db) {
var Model = require('../models/activities.js');
this.model = new Model(db);
this.async = require('async');
};
这定义了一个局部变量,它是一个函数。如果您尝试创建构造函数,则需要执行以下操作:
function Controller(db) {
var Model = require('../models/activities.js');
this.model = new Model(db);
this.async = require('async');
};
下面的上下文中的“this”指的是最外层的范围,因为Controller不是一个类型,而是一个本地函数。