Created
March 20, 2012 23:11
-
-
Save TheDahv/2142285 to your computer and use it in GitHub Desktop.
Teach Cromer how to do JavaScript
This file contains hidden or 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
// wrapped in anonymous function to protect against | |
// leaks to global NS | |
(function () { | |
// Factory to create objects | |
var make_thing = function (initial_value) { | |
var thing = that = {}; | |
thing.value = initial_value; | |
thing.dosomething = function () { | |
return that.value; // 'that' is 'closed over' | |
}; | |
return thing; | |
}; | |
var object_array = []; | |
var herp = function (objects) { | |
objects[0] = make_thing(1); | |
}; | |
var derp = function (objects) { | |
return objects[0].dosomething(); | |
}; | |
herp(object_array); | |
var result = derp(object_array); | |
console.log(result); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah, I wasn't really going for 'hiding' or doing any public/private things. That is definitely an important pattern with JavaScript objects.
Declaring a "that" variable is making use of closures in JavaScript to disambiguate what the the current "this" is when that function executes.