Skip to content

Instantly share code, notes, and snippets.

@TheDahv
Created March 20, 2012 23:11
Show Gist options
  • Save TheDahv/2142285 to your computer and use it in GitHub Desktop.
Save TheDahv/2142285 to your computer and use it in GitHub Desktop.
Teach Cromer how to do JavaScript
// 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);
}());
@mahmoud
Copy link

mahmoud commented Mar 21, 2012

Unless you have a specific reason, factories > constructors.

@TheDahv
Copy link
Author

TheDahv commented Mar 21, 2012

@makuro makes a good point. My assumption was Cromer was dealing with a "Thing" that he didn't have much control over.

@TheDahv
Copy link
Author

TheDahv commented Mar 21, 2012

Kind of a contrived example...

@mahmoud
Copy link

mahmoud commented Mar 22, 2012

I don't think 'thing' is any more protected than 'that'. They are both references to the same object. Changing 'thing' also changes 'that'.

@TheDahv
Copy link
Author

TheDahv commented Mar 22, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment