Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"this" is not what I think it is (from within a prototyped method)

I'm building out a Controller function in my Node application. For whatever reason, this is not what I think it is from within the prototyped method. I assumed (perhaps wrongly) that this would be an instance of the Controller. What am I doing wrong here?

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;
like image 247
Josh Smith Avatar asked Dec 17 '25 15:12

Josh Smith


1 Answers

You never construct an instance of Controller in the code you show.

module.exports = Controller;

is passing the constructor out to client modules, but to construct an instance you would have to do

module.exports = new Controller;

Alternatively, if you want other modules to create a Controller using the exports, they will have to use the new operator.

like image 51
Mike Samuel Avatar answered Dec 19 '25 06:12

Mike Samuel