问题
I'm diving more into Prototypal Inheritance with JavaScript. When Object.Create() is in use to create objects, can someone show what is going on under the hood? Does Object.Create() depend on new and constructor functions behind the scenes?
回答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
function create(proto, descriptors) {
return Object.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
function new(constructor, arguments) {
var instance = Object.create(constructor.prototype);
constructor.apply(instance, arguments);
return instance;
}
回答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 new object 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:
function AnotherObject() {
Base.call(this);
}
AnotherObject.prototype.constructor = AnotherObject;
来源:https://stackoverflow.com/questions/49116846/what-is-object-create-doing-under-the-hood