Created
August 24, 2011 18:09
-
-
Save webxl/1168731 to your computer and use it in GitHub Desktop.
new & this vs. module pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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