Reputation: 3511
I'm trying to implement the modular pattern:
var mod1, mod2;
mod1 = (function (mod2) {
var obj = {};
obj.whichMod = function () {
mod2.whichMod();
};
return obj;
}(mod2));
mod2 = (function (mod1) {
var obj = {};
obj.whichMod = function () {
console.log('mod2');
}
return obj;
}(mod1));
mod1.whichMod();
When I call mod1.whichMod() method, it says mod2 is not undefined. Why is this?
I want mod1.whichMod() to call mod2.whichMod() but mod2 should be "defined" after mod1 like shown above.
Upvotes: 0
Views: 43
Reputation: 3289
The problem is that you are using the closure which executes immediately. This is taking the new 'obj' and placing the 'undefined' mod2 and stuffing it into the whichMod function. When you go to call that function later it has no way of updating its reference which was undefined. The reason 'this' works is because you are returning the actual closure which has access to the mod2 variable which you then define later. This allows the mod2 to be updated. Below is an example of it not getting updated.
jsFiddle: http://jsfiddle.net/lookitstony/fzsodx85/
var mod1, mod2;
mod2 = {};
mod2.whichMod = function(){ console.log('first') };
mod1 = (function (mod2) {
var obj = {};
obj.whichMod = function () {
mod2.whichMod();
};
return obj;
}(mod2));
mod2 = (function (mod1) {
var obj = {};
obj.whichMod = function () {
console.log('mod2');
}
return obj;
}(mod1));
$(function(){
mod1.whichMod(); // mod2 did not exist so its using the one defined above
mod2.whichMod(); // mod2 is now overwritten but....
mod1.whichMod(); // mod1 still has the original object passed in
});
Upvotes: 1