Skip to content

Instantly share code, notes, and snippets.

@gartenfeld
Created February 11, 2016 22:23
Show Gist options
  • Select an option

  • Save gartenfeld/b83db39168d21f881e8b to your computer and use it in GitHub Desktop.

Select an option

Save gartenfeld/b83db39168d21f881e8b to your computer and use it in GitHub Desktop.
An Illustrative Tale of JavaScript Behaviours
function setLoader(store) {
// Now `store` is imported into the closure scope
return function set(val) {
/**
* To update a value, reassign a property, not a variable
* For example, `store = { value: 'new value' };` would NOT
* work. It just reassigns the scope variable `store` to
* point to something else, rather than going to the memory
* spot of what `store` points to and alter the value there
*/
store.value = val;
};
}
function Thing() {
var _store = { value: '' };
this.set = setLoader(_store);
this.get = function() {
return _store.value;
};
}
var a = new Thing();
var b = new Thing();
a.set(10);
console.log(a.get()); // 10
// Each instance gets its own separate `store`
b.set(20);
console.log(a.get()); // 10
console.log(b.get()); // 20
/**
* Use an expression, not declaration, lest it be hoisted!
* If it were a declaration and hoisted, the first definition
* above would get overridden, before `a` and `b` even get a
* chance to use the old behaviour
*/
var setLoader = function(store) {
return function set(val) {
store.value = 'New Behaviour! ' + val;
};
}
console.log(a.get());
var c = new Thing();
c.set(42);
console.log(c.get()); // New Behaviour! 42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment