Javascript 为什么 String(null) 有效?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10362114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:02:12  来源:igfitidea点击:

Why does String(null) work?

javascriptstringnulltostring

提问by KooiInc

nulland undefineddon't have a toStringor valueOfmethod. Afaik using Stringcalls the toStringmethod of its parameter (e.g. String({})=> [object Object]).

null并且undefined没有toStringorvalueOf方法。Afaik usingString调用toString其参数的方法(例如String({})=> [object Object])。

Why do String(null)or String(undefinedwork then? It doesn't implicitly do Object.prototype.toString.call(null). because that evaluates to [object Null].

那为什么要工作String(null)String(undefined工作呢?它不会隐含地做Object.prototype.toString.call(null)。因为它评估为[object Null].

[edit]: from the spec ECMA-262/5th edition (page 48). This doesn't add to clarification, I'd say:

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

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

回答by Corbin

After reviewing my previous answer, it seems a complete overhaul of my previous answer is necessary. I was way over complicating it, as the short answer is that these are standards-specified special cases.

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

The specificationfor String()(Stringused as a function):

规范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.

15.5.1.1 字符串([值])

返回由 ToString(value) 计算的 String 值(不是 String 对象)。如果未提供 value,则返回空字符串 ""。

The ToStringfunction (that exists internally, not in userland) is defined as follows (9.8):

ToString功能(即在内部存在,而不是在用户级)被定义如下(9.8):

"The abstract operation ToString converts its argument to a value of type String according to Table 13"

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

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

This means that String(null)and String(undefined)go into this special table of types and just return the string values valued "null"and "undefined".

这意味着String(null)andString(undefined)进入这个特殊的类型表并只返回值为"null"and的字符串值"undefined"

A user-land pseudo-implementation looks something like this:

用户态伪实现如下所示:

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

(Note that this example ignores the constructor case (new MyString()) and that it uses user-land concepts rather than engine-land.)

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



I got a bit carried away and found an example implementation (V8 to be specific):

我有点忘乎所以,找到了一个示例实现(具体来说是 V8):

string.js:

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:

macros.py:

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

runtime.js:

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

The NonStringToString (which is essentially what is of interest), is luckily defined in psuedo-JS-land. As you can see, there is indeed a special case for null/true/false/undefined.

NonStringToString(本质上是感兴趣的),幸运的是在 psuedo-JS-land 中定义。如您所见,确实存在 null/true/false/undefined 的特殊情况。

回答by Thilo

There is probably just some extra checks and handling for special cases like nulland undefined.

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

MDN says:

MDN 说

It's possible to use String as a "safer" toString alternative, as although it still normally calls the underlying toString, it also works for null and undefined.

可以将 String 用作“更安全”的 toString 替代方案,尽管它通常仍会调用底层 toString,但它也适用于 null 和 undefined。

回答by Dan D.

You might be interested in seeing the Annotated ES5(which is much more readable than the ECMAScript 5 PDF) which states that: new String([ value ])http://es5.github.com/#x15.5.2.1calls [ToString]http://es5.github.com/#x9.8(there is a table of the special convertion cases) to convert the value passed to it to a string.

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

回答by robrich

String(null)creates a string object and passes it a default value of null.

String(null)创建一个字符串对象并将默认值传递给它。