gpt4 book ai didi

javascript - Chrome 的 Javascript 控制台 : what does it output in terms of objects?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:09:47 25 4
gpt4 key购买 nike

从 Chrome 中的 javascript 控制台:

> function Person(name){this.name=name;}
undefined

此时,根据 Javascript 规范,Person.prototype 应该是一个空对象。让我们分配它:

> p=Person.prototype
> Person

请注意,> Person 是可点击的,它会扩展为:

constructor: function Person(name){this.name=name;}
__proto__: Object

但是……它不应该是一个空对象吗?什么是所有额外的东西?如果您发出警报:

alert(p)

你得到 [object 对象]。为什么,当您在 Chrome 控制台中键入它时,会出现 > Person 展开?这不是一个空对象吗?

谢谢!

最佳答案

不,prototype 始终具有 constructor 属性,该属性指向作为其原型(prototype)的函数。当然它也继承自一个对象,即内部 __proto__ 属性。

它在 ECMAScript 5 Section 13.2, Creating Function Objects 中定义:

(...)

16. Let proto be the result of creating a new object as would be constructed by the expression new Object() where Object is the standard built-in constructor with that name.

17. Call the [[DefineOwnProperty]] internal method of proto with arguments "constructor", Property Descriptor {[[Value]]: F, { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true}, and false.

18. Call the [[DefineOwnProperty]] internal method of F with arguments "prototype", Property Descriptor {[[Value]]: proto, { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false}, and false.

(...)

这意味着:

创建一个名为 proto 的新空对象 (16)。在该对象上定义属性 constructor 并将值设置为 F(函数本身)(17)。然后在函数 F 上定义属性 prototype 并将其值设置为 proto


如果您警告 一个对象,那么该对象将被转换为一个字符串。默认行为是将对象转换为 [object Object] 字符串,除非“特殊”toString 方法被覆盖。

Chrome 控制台列出了这些属性,因为它用于调试,因此您需要信息。 [object Object] 信息量不大。

FWIW,一个空对象看起来像这样:

empty object

您还可以在此处查看内部 __proto__ 属性。空对象总是继承一些默认属性,但它没有自己的属性。

关于javascript - Chrome 的 Javascript 控制台 : what does it output in terms of objects?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6553951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com