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
Null prototype, Object.prototype and Object.create
提问by Duncan
Why is it that setting the prototype property of a constructor function to null
does 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 new
operator will alwayshave an object prototype in this case Object.prototype
and 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 new
operator 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.create
we 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 Foo
is Object.prototype
and not null
. It is impossible to create objects with no prototype without Object.create
using standard methods only.
所以被调用的对象的原型new Foo
是Object.prototype
和不是null
。如果Object.create
只使用标准方法,就不可能创建没有原型的对象。