javascript - 为什么 String(null) 有效?

标签 javascript string null tostring

nullundefined 没有 toStringvalueOf 方法。 Afaik 使用 String 调用其参数的 toString 方法(例如 String({}) => [object Object])。

为什么 String(null)String(undefined) 可以工作?它不会隐式执行 Object.prototype.toString.call(null)。因为其计算结果为 [object Null]

[编辑]:来自规范 ECMA-262/5 版(第 48 页)。我想说,这并没有增加澄清:

/*
Table 13 — ToString Conversions  
-------------------------------------------------------------------------
Argument Type  | Result  
-------------------------------------------------------------------------
Undefined      | "undefined"
Null           | "null"  
Boolean        | If the argument is true, then the result is "true".
...            | ...
*/

最佳答案

回顾我之前的答案后,似乎有必要对我之前的答案进行彻底修改。我把它复杂化了,因为简短的答案是这些是标准指定的特殊情况。

specification for String() (String 用作函数):

15.5.1.1 String ( [ value ] )

Returns a String value (not a String object) computed by ToString(value). If value is not supplied, the empty String "" is returned.

ToString 函数(存在于内部,而不是用户态)定义如下 (9.8):

“抽象操作 ToString 根据表 13 将其参数转换为 String 类型的值”

Argument Type | Result
Null | "null"
Undefined | "undefined"

这意味着 String(null)String(undefined) 进入这个特殊的类型表并仅返回值为 "null"< 的字符串值“未定义”

用户态伪实现看起来像这样:

function MyString(val) {
    if (arguments.length === 0) {
        return "";
    } else if (typeof val === "undefined") {
        return "undefined";
    } else if (val === null) {
        return "null";
    } else if (typeof val === "boolean") {
        return val ? "true" : "false";
    } else if (typeof val === "number") {
        // super complex rules
    } else if (typeof val === "string") {
        return val;
    } else {
        // return MyString(ToPrimitive(val, prefer string))
    }
}

(请注意,此示例忽略构造函数情况 (new MyString()),并且它使用用户域概念而不是引擎域概念。)

<小时/>

我有点得意忘形,找到了一个示例实现(具体是 V8):

string.js:

// Set the String function and constructor.
%SetCode($String, function(x) {
  var value = %_ArgumentsLength() == 0 ? '' : TO_STRING_INLINE(x);
  if (%_IsConstructCall()) {
    %_SetValueOf(this, value);
  } else {
    return value;
  }
});

宏.py:

macro TO_STRING_INLINE(arg) = (IS_STRING(%IS_VAR(arg)) ? arg : NonStringToString(arg));

runtime.js:

function NonStringToString(x) {
  if (IS_NUMBER(x)) return %_NumberToString(x);
  if (IS_BOOLEAN(x)) return x ? 'true' : 'false';
  if (IS_UNDEFINED(x)) return 'undefined';
  return (IS_NULL(x)) ? 'null' : %ToString(%DefaultString(x));
}

幸运的是,NonStringToString(这本质上是我们感兴趣的)是在 psuedo-JS-land 中定义的。正如您所看到的,null/true/false/undefined 确实有一种特殊情况。

关于javascript - 为什么 String(null) 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10362114/

相关文章:

java - 如何在泛型中实现空对象模式?

javascript - 将oauth与Electron结合使用时出现问题

javascript - 代码在 Fiddle 上运行但不在网站上运行

javascript - 在浏览器上使用 Javascript require 和 import

ruby - 为什么 YAML 在字符串上抛出 float ArgumentErrors?

ios - 超出范围后 NSError 为 nil

javascript - 使用 JQuery 顺序调用 Javascript 文件

php - 在 [ 和 ] 之间匹配的正则表达式

c - 打印字符串时出现意外结果

sql - 为什么 Oracle 9i 将空字符串视为 NULL?