The Object.create()
method was introduced in ES5. It creates a new object, using its first argument as the prototype of that object:
1 | Object.create(proto, [propertiesObject]) |
The first argument could only an object or null
, otherwise a TypeError
will be thrown.
1 | var plainObj = { prop1: 'prop1 value' }; |
You can pass null
to create a new object that does not have a prototype, in this case the newly created object will not inherit anything, not event basic methods like toString()
:
1 | var obj = Object.create(null); // create a 'null' object |
If you want to create an ordinary empty object, pass Object.prototype
or {}
:
1 | var obj1 = Object.create({}); |
Object.create()
also takes an optional second argument that describes the properties of the new object. These properties correspond to the second argument of Object.defineProperties()
.
1 | // Example where we create an object with a couple of |
Classical inheritance with Object.create()
Below is an example of how to use Object.create() to achieve classical inheritance. This is for a single inheritance, which is all that JavaScript supports.
1 | // Shape - superclass |
If you wish to inherit from multiple objects, then mixins are a possibility.
1 | function MyClass() { |
Object.assign()
copies properties from the OtherSuperClass
prototype to the MyClass
prototype, making them available to all instances of MyClass
. Object.assign()
was introduced with ES2015 and can be polyfilled. If support for older browsers is necessary, jQuery.extend()
or _.assign()
can be used.
Polyfill
This polyfill covers the main use case, which is creating a new object for which the prototype has been chosen but doesn’t take the second argument into account.
Note that while the setting of null as [[Prototype]] is supported in the real ES5 Object.create, this polyfill cannot support it due to a limitation inherent in versions of ECMAScript lower than 5.
1 | if (typeof Object.create !== "function") { |
Ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create