What Is Object.create() Doing Under The Hood?
Solution 1:
When
Object.create()
is in use to create objects, can someone show what is going on under the hood?
Low level details. Object.create
is pretty much a primitive operation - similar to what happens when an {}
object literal is evaluated. Just try to understand what it is doing.
That said, with new ES6 operations it could be implemented in terms of
functioncreate(proto, descriptors) {
returnObject.defineProperties(Object.setPrototypeOf({}, proto), descriptors);
}
Does
Object.create()
depend onnew
and constructor functions behind the scenes?
No, not at all. It's the reverse rather. The new
operator could be implemented as
functionnew(constructor, arguments) {
var instance = Object.create(constructor.prototype);
constructor.apply(instance, arguments);
return instance;
}
Solution 2:
Object.create does not call "new" or the constructor function. It just set the prototype of the new object to the prototype of the object passed as parameter.
So
AnotherObject.prototype = Object.create ( Base.prototype )
creates the newobject and set AnotherObject.__proto__ to Base.prototype
When you call "new", besides calling the "create" (above) it also calls the Base class's constructor.
To extend, you can extend the new object's prototype as
AnotherObject.prototype.anotherMethod = function() {
// code for another method
};
If you need a new new constructor for the new object you can create it like:
functionAnotherObject() {
Base.call(this);
}
AnotherObject.prototype.constructor = AnotherObject;
Post a Comment for "What Is Object.create() Doing Under The Hood?"