Skip to content

Instantly share code, notes, and snippets.

@webxl
Created August 24, 2011 18:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save webxl/1168731 to your computer and use it in GitHub Desktop.
new & this vs. module pattern
function BigComputer(answer) {
this.the_answer = answer;
this.ask_question = function () {
return check_answer.call(this,this.the_answer);
}
function check_answer(ans) {
console.log(this instanceof BigComputer);
return this.the_answer;
}
}
var deep_thought = new BigComputer(42);
var the_meaning = deep_thought.ask_question();
console.log(the_meaning)
// ht: http://www.digital-web.com/articles/scope_in_javascript/
function BigComputer(answer) {
var the_answer = answer;
var ask_question = function () {
return check_answer(the_answer);
}
function check_answer(ans) {
return the_answer;
}
return {
ask_question: ask_question
}
}
var deep_thought = BigComputer(42);
var deep_thought2 = BigComputer(22);
var the_meaning = deep_thought.ask_question();
var the_meaning2 = deep_thought2.ask_question();
console.log(the_meaning) // 42
console.log(the_meaning2) // 22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment