Skip to content

Instantly share code, notes, and snippets.

@sirbarrence
Created March 13, 2013 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sirbarrence/5152905 to your computer and use it in GitHub Desktop.
Save sirbarrence/5152905 to your computer and use it in GitHub Desktop.
Short illustration of what `this` means in various scopes, when using a constructor function approach.
var WhatIsThis = function () {
var _this = this; // `_this` or `that` or `self`, take your pick
// References to Window below assume you're running in a browser and not node.js
console.log("'this' directly in constructor body: ", this); // 'this' is WhatIsThis
function privateFunc() {
console.log("'this' in privateFunc: ", this); // 'this' is Window
console.log("'_this' in privateFunc: ", _this); // '_this' is WhatIsThis
}
this.publicFunc = function () {
console.log("'this' in publicFunc: ", this); // 'this' is WhatIsThis
console.log("'_this' in publicFunc: ", _this); // '_this' is WhatIsThis
console.log("calling private functions from public function");
privateFunc();
alsoPrivateFunc();
};
var alsoPrivateFunc = function () {
console.log("'this' in alsoPrivateFunc: ", this); // 'this' is Window
console.log("'_this' in alsoPrivateFunc: ", _this); // '_this' is WhatIsThis
};
console.log("calling private functions from constructor");
privateFunc();
alsoPrivateFunc();
};
WhatIsThis.prototype.otherPublicFunc = function () {
console.log("'this' in otherPublicFunc: ", this); // 'this' is WhatIsThis
// cannot call functions or reference variables that are private to the
// constructor function scope here.
//console.log("'_this' in otherPublicFunc: ", _this); // ERROR
//privateFunc(); // ERROR
//alsoPrivateFunc(); // ERROR
};
var inst = new WhatIsThis();
inst.publicFunc();
inst.otherPublicFunc();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment