【问题标题】:how to get object's [[DefaultValue]]如何获取对象的 [[DefaultValue]]
【发布时间】:2011-04-28 07:08:50
【问题描述】:

根据 ecma262-3 8.6.2.6 [DefaultValue]
http://bclary.com/2004/11/07/#a-8.6.2.6
现在我想获得 [] 的 [[DefaultValue]]
所以根据 ecma,像这样:
当 O 的 [[DefaultValue]] 方法用提示 Number 调用时,将采取以下步骤:
1.使用参数“valueOf”调用对象 O 的 [[Get]] 方法。
[ ].valeOf() => [ ]//本身
2.如果 Result(1) 不是对象,请转到步骤 5。
[ ] 是对象
3.调用 Result(1) 的 [[Call]] 方法,使用 O 作为 this 值和一个空参数列表。
Result(1) => [ ],[ ] 不要实施 [[Call]]
4.如果 Result(3) 是原始值,则返回 Result(3)。
所以,没有 Result(3),否则仍然是 [ ]
5.使用参数“toString”调用对象 O 的 [[Get]] 方法。
[ ].toString => ""
6.如果 Result(5) 不是对象,请转到第 9 步。
Result(5) => "" 不是对象,请转到第 9 步
7。调用 Result(5) 的 [[Call]] 方法,其中 O 为 this 值,参数列表为空。
8. 如果 Result(7) 是原始值,则返回 Result(7)。
9. 抛出 TypeError 异常。
错误?天哪!

【问题讨论】:

    标签: javascript ecma262


    【解决方案1】:

    在数组对象上调用的[[DefaultValue]] 最终会到达(并调用)数组对象的toString 方法。该方法本质上是一个Array.prototype.toString,它与在数组对象上调用Array.prototype.join 相同(参见15.4.4.2)。因此,空数组对象上的toString 返回空字符串 (""),它原始值,因此从 [[DefaultValue]] 内部方法返回。

    所以数组的 [[DefaultValue]] 是一个空字符串 - 如果 Array.prototype.string 没有被覆盖/隐藏,并且如果 Array.prototype.valueOf 没有被覆盖/隐藏.

    []+''; // ""
    
    Array.prototype.toString = function(){return 1};
    []+''; // "1"
    
    Array.prototype.valueOf = function(){return 2};
    []+''; // "2"
    

    【讨论】:

      猜你喜欢
      • 2020-11-28
      • 1970-01-01
      • 2023-02-05
      • 2022-01-11
      • 2011-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      相关资源
      最近更新 更多