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

时间:2018-03-05 18:09:08

标签: javascript prototypal-inheritance

我更多地使用JavaScript进行Prototypal Inheritance。当Object.Create()用于创建对象时,是否有人可以显示引擎盖下的内容? Object.Create()是否依赖于幕后的新函数和构造函数?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

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

所以

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

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

当你打电话给" new"时,除了打电话给"创建" (上图)它还调用Base类的构造函数。

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

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

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

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

AnotherObject.prototype.constructor = AnotherObject;