Implementation 1:
Working code in normal
var foo1 = function() {
var t1 = new Date();
console.log("initialize - one time only " + this);
foo1 = function() {
console.log("Executes every time after initializing (initialize should not execute again) " + this);
return t1;
};
return foo1();
};
Executing: foo1();
Output:
First Time
Initialize - one time only [object Window]
Executes every time after initializing (initialize should not execute again) [object Window]
Every Other Time
Executes every time after initializing (initialize should not execute again) [object Window]
Implementation 2
Trying the same in a JavaScript module
var tt=(function(){
var foo = function() {
var that=this;
var t = new Date();
console.log("initialize - one time only" + this);
foo = function() {
console.log("Executes every time after initializing(initialize should not execute again) "+this);
return t;
};
return foo();
}
return {
foo:foo
};
})();
Execute: tt.foo();
Output:
First Time
Initialize - one time only [object Object]
Executes every time after initializing(initialize should not execute again) [object Window]
Every Other Time
Initialize - one time only [object Object]
Executes every time after initializing(initialize should not execute again) [object Window]
Why does foo1 initialize again in method 2?
Why does the scope of this change inside the module pattern to window in method 2?
How can we make method 2 work like in method 1?
Please provide a conceptual explanation of what is wrong with method 2. Thank you in advance.