If I want to create an object in JavaScript that has a prototype link to another object, but has several of it's own properties how can I do this?
var object1 = {
a: 1,
b: 2
};
var object2 = Object.create( object1 );
object2.c = 3;
object2.d = 4;
console.log( object2 ); // my new object with object1 as it's prototype link
My challenge here is that I have to set object2
's properties one at a time.
My other option is:
var object1 = {
a: 1,
b: 2
};
var object2 = {
c: 3,
d: 4
};
Object.setPrototypeOf( object2, object1 );
console.log( object2 );
My challenge above is that the performance is supposed to be terrible. Namely, setPrototypeOf
is slow. https://jsperf.com/object-create-vs-object-setprototypeof
And then of course, there's the "shorthand" where you provide, writeable
, enumerable
and all that to Object.create()
, but that's not really shorthand.
Any ideas?
Normally, when we talk about setting and swapping prototypes, we are talking about constructor functions that are instantiated into objects and not object literals themselves.
You can certainly, just manually switch the prototype yourself in this case (which is the basis for prototypical inheritance) and will cause you to inherit the right properties, but you also now have to deal with constructor issues when instances of your derived object get made.
But, this technique is fast as it only requires a new instance to be made and that reference is then set in the prototype property.
You can combine
Object.create
withObject.assign
for this:As an alternative to
Object.assign
, rememberObject.create
accepts a second argument with the property descriptors you want to add to the object:Note the default is non-configurable, non-writable and non-enumerable.
If that's a problem, ES2017 introduces
Object.getOwnPropertyDescriptors
.