为什么字符串(空)的工作?(Why does String(null) work?)

2019-06-24 00:38发布

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".
...            | ...
*/

Answer 1:

回顾我以前的答复后,看来我以前的答案的全面改革是必要的。 我一路过来复杂化它,简单的答案是,这些标准规定的特殊情况。

的规范为String() String用作函数):

15.5.1.1字符串([值])

返回的ToString(值)计算出的值的字符串(未字符串对象)。 如果没有提供值,空字符串“”返回。

所述ToString函数(即在内部存在,而不是在用户级)被定义如下(9.8):

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

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

这意味着String(null)String(undefined)进入的种类这个特殊的表格,就回到看重的字符串值"null""undefined"

用户-土地伪实施看起来是这样的:

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;
  }
});

macros.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(这基本上是什么利息),在伪JS-幸运地定义。 正如你所看到的,的确是空/真/假/未定义的一个特例。



Answer 2:

有可能只是一些额外的检查和处理的特殊情况下,像nullundefined

MDN说 :

它可以使用String作为一个“更安全”的toString的选择,因为尽管它仍然正常调用底层的toString,它也适用于null和undefined。



Answer 3:

您可能会感兴趣的看到注释ES5 (这是比的ECMAScript 5 PDF更可读),其中指出: new String([ value ]) http://es5.github.com/#x15.5.2.1调用[ToString] http://es5.github.com/#x9.8 (有特殊情况皈依表)传递给它的字符串值转换。



Answer 4:

String(null)创建了一个字符串对象,并将其传递空的默认值。



文章来源: Why does String(null) work?