__proto__ 的值是如何在 javascript 中赋值的? [英] How value to __proto__ is assigned in javascript?

查看:53
本文介绍了__proto__ 的值是如何在 javascript 中赋值的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在玩 javaScript 原型对象,遇到了下面的例子.

Recently I have been playing with javaScript prototype object and came across below example.

function Foo(){ 

}

Foo.prototype=null;

var fooObj=new Foo();

当我从开发者工具查看 fooObj 时,__proto__ 属性指向全局对象的原型,我可以访问对象的原型对象中定义的所有属性和函数.它应该指向 Foo 函数的原型对象,因为我已经为它分配了 null 我期望 __proto__ 将指向 null,指向 __proto__ 可能更有意义,但我想了解创建对象后如何为 __proto__ 赋值?是什么导致它指向 Object 的原型对象?

When I look at the fooObj from developer tools, the __proto__ property points to the global Object's prototype and I can access all properties and function defined in Object's prototype object. which should point to Foo function's prototype object, since I have assigned null to it I was expecting __proto__ will point to null, Pointing __proto__ might make more sense but I want to understand how value is assigned to __proto__ after object creation? what is causing it to point Object's prototype object?

我看过很多关于prototype和proto的问题,但没有一个能解决我的疑惑.

I have seen many questions on prototype and proto but none of them solves my doubts.

推荐答案

规范*,但是当您使用带有 null 的构造函数作为其 prototype 属性时,newObject.prototype(好吧,领域的默认原型;Object.prototype 用于我们的目的)作为新对象的原型.

Full details in the specification*, but when you use a constructor function with null for its prototype property, new assigns Object.prototype (well, the default prototype for the realm; Object.prototype for our purposes) as the prototype of the new object.

我相信创建没有原型的对象的唯一方法是Object.create(null).

I believe the only way to create an object with no prototype is Object.create(null).

您可以在通过Object.setPrototypeOf创建对象后set原型为null,但通常最好避免更改对象的创建原型后.

You can set the prototype to null after creating the object via Object.setPrototypeOf, but in general it's best to avoid changing an object's prototype after you've created it.

* 具体来说,它隐藏在 GetPrototypeFromConstructor,表示如果构造函数的 prototype 属性的类型不是 Object(为此,null 是 Null 类型,不输入对象),使用领域的默认原型.

* Specifically, it's tucked away in GetPrototypeFromConstructor, which says if the type of the constructor's prototype property isn't Object (for this purpose, null is of type Null, not type Object), use the default prototype for the realm.

这篇关于__proto__ 的值是如何在 javascript 中赋值的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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