Skip to content

Instantly share code, notes, and snippets.

@dandean
Created October 24, 2010 04:21
Show Gist options
  • Select an option

  • Save dandean/643084 to your computer and use it in GitHub Desktop.

Select an option

Save dandean/643084 to your computer and use it in GitHub Desktop.
Creating dynamically named getters and setters on an object
/**
* And this is the winning version thanks to @gf3. Using Object.keys().forEach()
* is faster than for..in as benchmarked by @creationix here:
* https://gist.github.com/75d0278890e6c5833add
* According to @jdalton, this is because for..in looks up the prototype chain
* while Object.keys looks at own keys.
**/
var obj1 = {
a: "a",
b: "b",
c: "c"
};
var obj2 = {};
Object.keys( obj1 ).forEach( function( key ) {
obj2.__defineGetter__(key, function() {
return obj1[key];
});
});
console.log(obj2.a, obj2.b, obj2.c);
// EXPECTED:
// --> a
// --> b
// --> c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment