I am surprised that I could not find more on this topic (could be my sub-par search skills). Typically once I think I understand how the JavaScript keyword, "this" works it then stops working the way I understand. I'll address one such issue.
My understanding: "When a function is called using the 'new' keyword ... 'this' refers to the root function/'class'. When used from functions within the instantiated 'class' this refers to the CALLING function". -- This is very important to understand: when the function is called from another function on the page the 'this' keyword will refer calling function and not the 'class' within which the target function lives.
In the following example I have tried two ways to set a variable from a public function. Both fail. I am attempting to understand why this is and how to make this work.
var functionClass = new function(){
var _isReady = false;
var _getReady = function(){
// ... do some work to get ready
_isReady = true;
}
return {
IsReady: _isReady,
GetReady: _getReady
}
}
var functionClass1 = new function () {
var _isReady = false;
var _self = this;
var _getReady = function () {
// ... do some work to get ready
_self.IsReady = true;
}
return {
IsReady: _isReady,
GetReady: _getReady
}
}
functionClass.GetReady();
functionClass1.GetReady();
console.log(functionClass.IsReady); // Expect true ... I get false
console.log(functionClass1.IsReady); // Expect true ... I get false
UPDATE:
I Probably should point out that I am using the Revealing Module Pattern and would prefer that any solution be in that context. While I am sure there are a multitude of different ways of doing this I would like to focus the solution to this pattern.