“这个”不是我认为的(来自原型方法)

时间:2012-02-02 16:01:49

标签: javascript node.js

我正在我的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;

3 个答案:

答案 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不是一个类型,而是一个本地函数。