Created
March 13, 2013 14:56
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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