【问题标题】:What is Object.Create() doing under the hood?Object.Create() 在幕后做什么?
【发布时间】:2018-08-13 11:38:42
【问题描述】:

我更深入地研究使用 JavaScript 的原型继承。当 Object.Create() 用于创建对象时,有人可以展示幕后发生的事情吗? Object.Create() 是否依赖于幕后的 new 和构造函数?

【问题讨论】:

  • “Under the hood”是一种完全不同的编程语言,用于实现 JS 运行时,因此“new”和“constructor”之类的含义不同。
  • 你试过看v8 source?
  • 这是实现必须(语义)符合的规范部分:tc39.github.io/ecma262/#sec-object.create 这仅描述语义要求。实际的实现可能并且很可能非常不同。
  • polyfill example on MDN 应该很好地展示了这里发生的事情。它不处理额外的属性,只是基本的创建,但应该相当清楚。

标签: javascript prototypal-inheritance


【解决方案1】:

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;

【讨论】:

  • 我认为您的意思是“代替”而不是“除了”。这条线真的很混乱。
  • 不,它是“除了”。当您调用 new - 它执行“创建”+ 它调用基类的构造函数。它两者兼而有之。 Create 不调用基类的构造函数,"new" 会。
  • 哦,这就是你的意思。我修复了逗号以启用对措辞的解释:-)
【解决方案2】:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 2019-05-21
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多