Skip to content

Instantly share code, notes, and snippets.

@mgile
Created June 28, 2011 15:21
Show Gist options
  • Save mgile/1051375 to your computer and use it in GitHub Desktop.
Save mgile/1051375 to your computer and use it in GitHub Desktop.
callbacks from within a Javascript "class"
var MyClass = function() {
this.myObject = {};
this.name = "MyClass";
};
/**
* doSomethingWithFileData
* @param err
* @param fileData
*/
MyClass.prototype.doSomethingWithFileData = function(err, fileData) {
if(typeof this.myObject !== 'object' && this.name !== "MyClass") {
console.log("You fail! Scoping error, 'this' is not the 'this' you are looking for.");
console.log("'this': " + this);
console.log("\n\n");
}
else {
console.log("You win! 'this' is: " + this.name);
console.log("Here is your data: \n" + fileData);
console.log("\n\n");
}
};
MyClass.prototype.readFileAsync = function(filePath) {
// Wrong
fs.readFile(filePath, this.doSomethingWithFileData);
// Right
fs.readFile(filePath, CALLBACK(this, 'doSomethingWithFileData'));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment