什么是Object.Create()在幕后做什么?

问题描述 投票:2回答:2

我正在利用JavaScript进一步深入了解Prototypal Inheritance。当Object.Create()用于创建对象时,是否有人可以显示引擎盖下的内容? Object.Create()是否依赖于幕后的新函数和构造函数?

javascript prototypal-inheritance
2个回答
1
投票

Object.create()用于创建物体时,有人可以展示引擎盖下发生的事情吗?

低级细节。 Object.create几乎是一个原始操作 - 类似于评估{}对象文字时发生的操作。试着了解what it is doing

也就是说,通过新的ES6操作,它可以实现

function create(proto, descriptors) {
    return Object.defineProperties(Object.setPrototypeOf({}, proto), descriptors);
}

Object.create()是否依赖于幕后的new和构造函数?

一点都不。反之亦然。 new运算符可以实现为

function new(constructor, arguments) {
    var instance = Object.create(constructor.prototype);
    constructor.apply(instance, arguments);
    return instance;
}

0
投票

Object.create不会调用“new”或构造函数。它只是将新对象的原型设置为作为参数传递的对象的原型。

所以

AnotherObject.prototype = Object.create ( Base.prototype )

creates the new object and set  AnotherObject.__proto__ to Base.prototype

当你调用“new”时,除了调用“create”(上面)之外,它还调用Base类的构造函数。

要扩展,可以将新对象的原型扩展为

AnotherObject.prototype.anotherMethod = function() {
  // code for another method
};

如果您需要新对象的新构造函数,您可以创建它:

function AnotherObject() {
  Base.call(this);
}

AnotherObject.prototype.constructor = AnotherObject;
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.