Object.create

Object.create() returns a new object with a prototype of the object you passed it.

var proto = { foo: 'bar' };
var newObject = Object.create(proto);

newObject.foo; //=> 'bar'
newObject.hasOwnProperty('foo'); //=> false

Inheritance

var o1 = { one: '1' };

var o2 = Object.create(o1);
o2.two = '2';

var o3 = Object.create(o2);
o3.three = '3';

var o4 = Object.create(o3);

Results in a prototype chain like:

Which means we can do:

o4.one; //=> 1
o4.two; //=> 2
o4.three; //=> 3

What about the second argument?

The second argument is not too exciting; it works as a convenient shortcut to Object.defineProperties(). In short Object.defineProperties allows you to define the properties of particular keys on your object.

I won’t go over the API for Object.defineProperties in this article, but you can read all about it on our ever trustworthy MDN.

Demo

comments powered by Disqus