What is a best practice for ensuring "this" context in Javascript?
javascript, this
Solution
Using closure. Basically any variable declared in function, remains available to functions inside that function :
var Example = (function() {
function Example() {
var self = this; // variable in function Example
function privateFunction() {
// The variable self is available to this function even after Example returns.
console.log(self);
}
self.publicFunction = function() {
privateFunction();
}
}
return Example;
})();
ex = new Example;
ex.publicFunction();
Problem
Here's a sample of a simple Javascript class with a public and private method (fiddle: http://jsfiddle.net/gY4mh/). ``` function Example() { function privateFunction() { // "this" is window when called. console.log(this); } this.publicFunction = function() { privateFunction(); } } ex = new Example; ex.publicFunction(); ``` Calling the private function from the public one results in "this" being the window object. How should I ensure my private methods are called with the class context and not window? Would this be undesirable?