空原型,Object.prototype和Object.create [英] Null prototype, Object.prototype and Object.create

查看:105
本文介绍了空原型,Object.prototype和Object.create的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么将构造函数的prototype属性设置为 null 不会阻止从该函数创建的对象调用上的方法Object.prototype ,与将原型设置为 Object.create(null)的方式相同吗?

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?

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

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


推荐答案

简而言之



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

In short

Yes, your observation is correct - a function constructed with the new operator will always have an object prototype in this case Object.prototype and this is indeed unlike a function created with Object.create.

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

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

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

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


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

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.



Object.create



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


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

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

这意味着我们可以设置它,它也明确地检查它在那个al中是null或Object gorithm(请按照规范的链接阅读:))

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

所以用<$ c $调用对象的原型c> new Foo 是 Object.prototype 而不是 null 。如果没有 Object.create ,只能使用标准方法创建没有原型的对象。

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.

这篇关于空原型,Object.prototype和Object.create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆