Created
October 24, 2010 04:21
-
-
Save dandean/643084 to your computer and use it in GitHub Desktop.
Creating dynamically named getters and setters on an object
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
| /** | |
| * 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