Javascript Objects and Execution Context: the Module Pattern

Javascript Objects and Execution Context: This demonstrates what happens when an instantiated object calls a private function with the global executions context.

by webxl

HTML

<script src="https://raw.github.com/gist/1168925/a656217680aea942742df702952a67243ac65a8d/logResult.js"></script>

JavaScript

// module

function BigComputerA(answer) {
    // prviate
    var the_answer = answer;
    function check_answer(ans) {
        return the_answer;
    }
        
    // new object that has access to the closure above
    return({ask_question: function() {
        return check_answer(the_answer);
    }});
}

var deep_thought = BigComputerA(42);
var the_meaning = deep_thought.ask_question();

logResult(the_meaning); 
logResult(deep_thought.check_answer); // private

// vs. prototype 

function BigComputerB(answer) {
    this.the_answer = answer;
    this.check_answer = function(ans) {
        return ans;
    }
}

BigComputerB.prototype.ask_question = function() {
    return this.check_answer(this.the_answer);
} 
    
deep_thought = new BigComputerB(42);
the_meaning = deep_thought.ask_question();

logResult(the_meaning); 
logResult(deep_thought.check_answer); // public