为什么Boolean原语不能调用原型toString()? [英] Why does Boolean primitive not call prototype toString()?

查看:148
本文介绍了为什么Boolean原语不能调用原型toString()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这段代码:

Boolean.prototype.toString = function toString() {
  return this.valueOf() ? '1' : '0';
};

var object = {
  true: 'true',
  false: 'false',
  1: '1',
  0: '0'
};

// "true" - this doesn't work
console.log('primitive', object[true]);
// "1" - but these do
console.log('primitive.toString()', object[true.toString()]);
console.log('instance', object[new Boolean(true)]);

为什么没有原语使用类的 toString 定义?对象键是字符串或符号,它们不能只是原始的布尔值。这就是为什么我很困惑。

Why doesn't the primitive use the class's toString definition? Object keys are either strings or symbols, they cannot just be raw booleans. This is why I'm confused.

推荐答案

因为规范是这样说的。
http://www.ecma-international.org/ecma- 262 / 6.0 / index.html#sec-tostring
在此表中定义了基元的字符串值。仅使用对象 ToPrimitive

Because the specifications says so. http://www.ecma-international.org/ecma-262/6.0/index.html#sec-tostring In this table the String values of primitives are defined. Only for Objects ToPrimitive is used.

该表告诉我们 ToString 对象 o ToString(ToPrimitive(o,string))

规范告诉我们如果使用Object调用 ToPrimitive ,我们必须按照以下步骤操作:

The Specification tells us that if ToPrimitive is called with an Object we have to follow these steps:

1. If PreferredType was not passed, let hint be "default".
2. Else if PreferredType is hint String, let hint be "string".
3. Else PreferredType is hint Number, let hint be "number".
4. Let exoticToPrim be GetMethod(input, @@toPrimitive).
5. ReturnIfAbrupt(exoticToPrim).
6. If exoticToPrim is not undefined, then
  a. Let result be Call(exoticToPrim, input, «hint»).
  b. ReturnIfAbrupt(result).
  c. If Type(result) is not Object, return result.
  d. Throw a TypeError exception.
7. If hint is "default", let hint be "number".
8. Return OrdinaryToPrimitive(input,hint).

@@ toPrimitive beeing set是一个特殊的因此我们现在必须查看 OrdinaryToPrimitive

@@toPrimitive beeing set is a special case so we now have to look at OrdinaryToPrimitive

1. Assert: Type(O) is Object
2. Assert: Type(hint) is String and its value is either "string" or "number".
3. If hint is "string", then
  a. Let methodNames be «"toString", "valueOf"».
4. Else,
  a. Let methodNames be «"valueOf", "toString"».
5. For each name in methodNames in List order, do
  a. Let method be Get(O, name).
  b. ReturnIfAbrupt(method).
  c. If IsCallable(method) is true, then
    i. Let result be Call(method, O).
    ii. ReturnIfAbrupt(result).
    iii. If Type(result) is not Object, return result.
6. Throw a TypeError exception.

所以这意味着返回值 ToPrimitive(o,string ) o.toString() toString(o.toString())是与 o.toString()相同。

So this means that the return value of ToPrimitive(o, "string") is o.toString() and toString(o.toString()) is the same as o.toString().

这篇关于为什么Boolean原语不能调用原型toString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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