gpt4 book ai didi

javascript - 当构造函数的原型(prototype)不是对象时如何创建对象?

转载 作者:行者123 更新时间:2023-11-29 16:06:08 25 4
gpt4 key购买 nike

我回答了这个问题:How do objects created?但是在我回答之后我也有一个问题。

function Bar() {
this.foo = true;
}
console.log('obj3');
Bar.prototype = 3;
var obj3 = new Bar();
console.log(obj3);
console.log(obj3.constructor === Bar);
console.log(obj3.constructor === Object);

console.log(Object.prototype === Object.getPrototypeOf(obj3));
console.log(obj3.foo);

Bar.prototype = 3,我的理论是,当 new Bar() 执行时,如 第 2 步,创建的对象应该链接到 Bar.prototype,但由于 Bar.prototype 的值不引用对象,因此隐式分配了一个默认值,即 对象.原型(prototype)

由于 object.prototype.constructor 引用了 Objectobj3.constructor 也引用了 Object,但是 obj3事实上的构造函数仍然是 Bar,因为第 1 步,这也可以通过 console.log(obj3.foo); 来证明;//真

我说的对吗?

@Leo 问我是否可以提供有关内部机制的更多信息。他在 Firefox Chrome Safari 上测试过,它们的行为都是一样的,他认为这应该是 ECMA-262 中明确规定的东西。然而,他还没有到正确的地方。但是我也没有找到任何可以支持我的论点的东西,因此我正在寻求您的帮助。您能否提供有关内部机制的更多信息?

最佳答案

是的,这在GetPrototypeFromConstructor中指定:

  1. Let proto be ? Get(constructor, "prototype").
  2. If Type(proto) is not Object, then

    1. Let realm be ? GetFunctionRealm(constructor).
    2. Let proto be realm's intrinsic object named intrinsicDefaultProto.

具体来说,它是这样工作的:

  1. <a href="http://www.ecma-international.org/ecma-262/7.0/#sec-new-operator" rel="noreferrer noopener nofollow">new</a> Bar()电话 Bar.<a href="http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-construct-argumentslist-newtarget" rel="noreferrer noopener nofollow">[[Construct]]</a>
  2. 使用
    初始化thisArgument OrdinaryCreateFromConstructor (新目标"%ObjectPrototype%")
  3. 返回一个继承自
    的对象 GetPrototypeFromConstructor (构造函数intrinsicDefaultProto)

所以如果 prototype不是对象,默认值为该领域的 %ObjectPrototype%。

请注意,它并不总是 Object.prototype :

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var win = iframe.contentWindow;
document.body.removeChild(iframe);
var F = win.Function("")
F.prototype = 5;
var proto = Object.getPrototypeOf(new F());
proto === Object.prototype; // false
proto === win.Object.prototype; // true

关于javascript - 当构造函数的原型(prototype)不是对象时如何创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41846565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com