JSFiddle - React, Tailwind, and code Playground
by Bryan Braun
CSS
/* Explanation:
When the revealing module IIFE is done running, foo seems like it could be represented like this:
var foo = {
getVal: function _getVal() { return 5; },
callGetVal: function _callGetVal() { return _getVal() }
};
But that's not quite correct. In this representation, foo.callGetVal() would not work. If you try calling this replacement code, here's what you'd get:
foo.callGetVal();
// result: Uncaught ReferenceError: _getVal is not defined(…)
It can't just call _getVal() and reach the other method. If anything, you would need `this` for an object to reference itself.
So why does the original code work?
When you call foo.callGetVal(), it doesn't then call foo.getVal(). It calls the original _getVal() function that existed inside the closure that was created when the original IFFE was running. That original _getVal function was preserved in the closure because it was DEFINED in the (anonymous) top function and REFERENCED in the nested _callGetVal. The foo.getVal and the original _getVal are two separate functions that are not connected.
This is the same situation as the one I described in http://jsfiddle.net/bryanbraun/uodq529p/3/, except using functions, not values.
In practice, this situation appears often when you are Spying on functions with a testing framework, like Jasmine. If you spy on foo.getVal, and then run foo.callGetVal, you will see nothing because the original _getVal has no Spy associated with it.
*/
JavaScript
// Revealing Module
var foo = (function() {
function _getVal() {
return 5;
}
function _callGetVal() {
return _getVal();
}
return {
getVal: _getVal,
callGetVal: _callGetVal
};
})();
console.log(foo.getVal()); // Returns 5
console.log(foo.callGetVal()); // Returns 5
// Overwrite getVal
foo.getVal = function _getVal() { return 10 };
console.log(foo.getVal()); // Returns 10
console.log(foo.callGetVal()); // Returns 5 <---- Why?