Joe*_*ong 2 javascript constructor prototype object
我回答了这个问题:如何创建对象? 但在我回答之后我也有一个问题.
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);Run Code Online (Sandbox Code Playgroud)
Bar.prototype = 3,我的理论是,在new Bar()执行时,如在步骤2中,创建的对象应该链接到Bar.prototype,但由于值Bar.prototype不引用对象,隐式地分配了默认值,即Object.prototype.
由于object.prototype.constructor的参考Object,obj3.constructor同时参考Object,但obj3的事实上的构造仍然是Bar因为,第1步,其也可以通过证明console.log(obj3.foo); // true.
我对吗?
@Leo问我是否可以提供有关内部机制的更多信息.他在Firefox Chrome Safari中对它进行了测试,它们的行为都相同,他认为它应该是ECMA-262中明确规定的内容.但是,他没有到正确的地方.但是我也找不到任何支持我的论点,因此我正在寻求你的帮助.您能否提供有关内部机制的更多信息?
是的,这是在GetPrototypeFromConstructor中指定的:
- 让proto成为?获取(构造函数,
"prototype").如果Type(proto)不是Object,那么
- 让领域成为?GetFunctionRealm(构造函数).
- 让proto成为realm的内在对象,名为intrinsicDefaultProto.
具体来说,它的工作原理如下:
new Bar() 电话 Bar.[[Construct]]"%ObjectPrototype%")因此,如果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
Run Code Online (Sandbox Code Playgroud)