gpt4 book ai didi

javascript - javascript 中的 "document.writeln(Object.prototype);"打印什么?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:05:52 26 4
gpt4 key购买 nike

我试过并得到以下输出:

[对象对象]

我熟悉向 Object.prototype 添加新函数,以便程序中的每个对象都继承该新函数。但我有点想知道这是如何实现的。我猜 Object 应该是类型

{
name: expression,
name: expression,
...
}

我还猜测 Object.prototype 应该是 Object 属性之一的键,该属性的值是“[object Object]”。现在请您告诉我我的理解是否正确?

我还想知道“[object Object]”中的“object”和“Object”有什么区别。我还想知道上面提到的任何对象是否与前面的“.prototype”相关。你能澄清一下吗?

当我尝试打印 Object.prototype.object、Object.prototype.Object、Object.prototype[object]、Object.prototype[Object] 和 Object.prototype[0] 时,我总是得到未定义的结果。如果原型(prototype)没有任何属性,我如何获得[object Object]?

最佳答案

object 始终存在,Object 来自 [[Class]] 内部属性的值,这就是为什么

Object.prototype.toString.call([]) === "[object Array]";
Object.prototype.toString.call("") === "[object String]";
Object.prototype.toString.call(new Date) === "[object Date]";

15.2.4.2 中有描述:

15.2.4.2 Object.prototype.toString ( ) # Ⓣ Ⓔ Ⓡ

When the toString method is called, the following steps are taken:

  1. If the this value is undefined, return "[object Undefined]".
  2. If the this value is null, return "[object Null]".
  3. Let O be the result of calling ToObject passing the this value as the argument.
  4. Let class be the value of the [[Class]] internal property of O.
  5. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

内部属性有点困惑。您可以在 8.6.2 阅读它们:

This specification uses various internal properties to define the semantics of object values. These internal properties are not part of the ECMAScript language. They are defined by this specification purely for expository purposes. An implementation of ECMAScript must behave as if it produced and operated upon internal properties in the manner described here. The names of internal properties are enclosed in double square brackets [[ ]].

顺便说一句,jQuery 和其他库在它们的 isArray 函数中使用了 Object.prototype.toString.call 技巧,因为即使所有帧的内部属性都是相同的尽管每一帧都有自己的 Array 内置版本。

关于javascript - javascript 中的 "document.writeln(Object.prototype);"打印什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8521410/

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