javascript 空原型、Object.prototype 和 Object.create

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18198178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:03:32  来源:igfitidea点击:

Null prototype, Object.prototype and Object.create

javascriptprototype

提问by Duncan

Why is it that setting the prototype property of a constructor function to nulldoes not prevent objects created from that function from calling through to methods on Object.prototype, in the same way that setting the prototype to Object.create(null)does?

为什么将构造函数的原型属性设置为null不会阻止从该函数创建的对象调用 on 方法Object.prototype,就像将原型设置为Object.create(null)一样?

That is, why is this the case:

也就是说,为什么会这样:

function Foo(){}
Foo.prototype = null;
console.log(new Foo().toString); //outputs function toString() { [native code] } (or whatever)

function Foo(){}
Foo.prototype = Object.create(null);
console.log(new Foo().toString); //output undefined

回答by Benjamin Gruenbaum

In short

简而言之

Yes, your observation is correct - a function constructed with the newoperator will alwayshave an object prototype in this case Object.prototypeand this is indeed unlike a function created with Object.create.

是的,您的观察是正确的 -在这种情况下,使用new运算符构造的函数将始终具有对象原型,这Object.prototype确实与使用 Object.create 创建的函数不同。



On why

关于为什么

One can see this behavior completely specified in the ES5 language specification on which JavaScript is based on. Let's see this.

可以在 JavaScript 所基于的 ES5 语言规范中看到完全指定的这种行为。让我们看看这个。

In new:

new

Quoting the specificationof the [[Construct]]method of functions that indicates how object creation using the newoperator is performed we can see that the following is specified:

引用[[Construct]]指示如何使用new运算符创建对象的函数方法的规范,我们可以看到指定了以下内容:

If Type(proto) is not Object, set the [[Prototype]] internal property of obj to the standard built-in Object prototype object as described in 15.2.4.

如果 Type(proto) 不是 Object,则将 obj 的 [[Prototype]] 内部属性设置为标准内置 Object 原型对象,如 15.2.4 所述。

In Object.create:

Object.create

On the other hand, if we check out The spec for Object.createwe can see that Object.create(o)specifies:

另一方面,如果我们查看规范,Object.create我们可以看到它Object.create(o)指定:

Set the [[Prototype]] internal property of obj to O.

将 obj 的 [[Prototype]] 内部属性设置为 O。

Which means we can set it, it also explicitly checks that it is null or Object in that algorithm (please dofollow the link to the spec and read it :))

这意味着我们可以设置它,它也明确确认它为空或对象在算法(请不要跟随链接到规范和阅读:))

So the prototype of the objects called with new Foois Object.prototypeand not null. It is impossible to create objects with no prototype without Object.createusing standard methods only.

所以被调用的对象的原型new FooObject.prototype和不是null。如果Object.create只使用标准方法,就不可能创建没有原型的对象。