Last active
April 15, 2016 13:50
-
-
Save shaunwallace/0c4f0ffd89325612f8ed to your computer and use it in GitHub Desktop.
Object.create()
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
/* | |
Object.create(); | |
creates a new object with the specified prototype object and properties | |
object.create(proto[, propertiesObject]); | |
*/ | |
var obj = Object.create({}); // creates an empty object and is equivalent to obj = {} or obj = Object.create(Object.prototype) | |
var obj1 = { | |
foo : 1, | |
bar : function() { | |
return 'Bar method called'; | |
} | |
}; | |
var obj2 = Object.create(obj1); // now obj2 has the properties and methods of obj1 as part of its prototype not as it "own" properties | |
Object.keys( obj1 ) // returns ["foo", "bar"] | |
Object.keys( obj2 ) // returns [] | |
/* | |
Its also possible to set some initial values on the object being created, these are the object's own properties | |
*/ | |
var obj3 = Object.create(obj1, { | |
baz : { | |
value : 'Hello World' | |
} | |
}); | |
Object.keys( obj3 ) // returns [] | |
/* | |
The above line will not output what is expected as there are additional properties that are defined by default | |
when settting the propertiesObject when using Object.create() which are configurable, enumerable, value, writable, get, and set | |
In order to enumerate through these properties on the newly created object you would need to set enumerable to true. | |
*/ | |
obj3.baz; // returns "Hello World" and it also has access to its prototype properties and methods |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment