0

What I'm trying to do is pretty trivial: I am creating an object, or better I'm defining a function that is instantiating the object, and then I have another function that reads from a file and gets a callback when the reading is finished. The function is assigned to the prototype of the object, so that it's created only once and not every time I'm creating a new instance of it.

var fs = require('fs');

var CrazyObject = function () {
    this.craziness = 'this is sooo crazy';
};

CrazyObject.prototype.crazyFunction = function (file) {
    fs.readFile(file, function (err, result) {
        // here i can't access the craziness!
    });

    // but here i can
};

exports.CrazyObject = CrazyObject;

As the example shows, the problem is that inside the callback I can't access the variable assigned when the object is created.

Alessandro Roaro
  • 4,665
  • 6
  • 29
  • 48

1 Answers1

3

Just bind your callback function to the correct context:

fs.readFile(file, (function (err, result) {
    console.log(this.craziness);
}).bind(this));
madox2
  • 49,493
  • 17
  • 99
  • 99