Javascript String(value) 与 value.toString() 有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3945202/
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-23 06:47:29  来源:igfitidea点击:

What's the difference between String(value) vs value.toString()

javascript

提问by AlfaTeK

Javascript has lot's of "tricks" around types and type conversions so I'm wondering if these 2 methods are the same or if there is some corner case that makes them different?

Javascript 在类型和类型转换方面有很多“技巧”,所以我想知道这两种方法是否相同,或者是否有一些极端情况使它们不同?

回答by CMS

They are not completely the same, and actually, the String constructor called as a function(your first example), will at the end, call the toStringmethod of the object passed, for example:

它们并不完全相同,实际上,作为函数调用的 String 构造函数(您的第一个示例)将在最后调用toString传递的对象的方法,例如:

var o = { toString: function () { return "foo"; } };
String(o); // "foo"

On the other hand, if an identifier refers to nullor undefined, you can't use the toStringmethod, it will give you a TypeErrorexception:

另一方面,如果标识符引用nullor undefined,则不能使用该toString方法,它会给您一个TypeError异常

var value = null;
String(null);     // "null"
value.toString(); // TypeError

The Stringconstructor called as a function would be roughly equivalent to:

作为String函数调用的构造函数大致相当于:

value + '';

The type conversion rules from Object-to-Primitiveare detailed described on the specification, the [[DefaultValue]]internal operation.

ObjectPrimitive的类型转换规则在规范、[[DefaultValue]]内部操作中有详细描述。

Briefly summarized, when converting from Object-to-String, the following steps are taken:

简单总结一下,从ObjectString 的转换时,采取了以下步骤:

  1. If available, execute the toStringmethod.
    • If the resultis a primitive, return result, else go to Step 2.
  2. If available, execute the valueOfmethod.
    • If the resultis a primitive, return result, else go to Step 3.
  3. Throw TypeError.
  1. 如果可用,执行该toString方法。
    • 如果result原始类型,则返回result,否则转到步骤 2。
  2. 如果可用,执行该valueOf方法。
    • 如果result原始类型,则返回result,否则转到步骤 3。
  3. TypeError

Given the above rules, we can make an example of the semantics involved:

鉴于上述规则,我们可以举一个涉及语义的例子:

var o = {
  toString: function () { return "foo"; },
  valueOf:  function () { return "bar"; }
};

String(o); // "foo"

// Make the toString method unavailable:
o.toString = null;

String(o); // "bar"

// Also make the valueOf method unavailable:
o.valueOf = null;

try { 
  String(o); 
} catch (e) {
  alert(e); // TypeError
}

If you want to know more about this mechanism I would recommend looking at the ToPrimitiveand the ToStringinternal operations.

如果您想了解更多关于这个机制,我会建议看ToPrimitiveToString内部操作。

I also recommend reading this article:

我还推荐阅读这篇文章:

回答by Jonathan

value.toString()will cause an error if valueis null. String(value)should not.

value.toString()如果value为空将导致错误。String(value)不应该。

For example:

例如:

var value = null;
alert(value.toString());

will fail because value == null.

会失败,因为value == null

var value = null;
alert(String(value));

should display a message reading "null" (or similar), but it will not crash.

应该显示一条消息“null”(或类似的),但它不会崩溃。

回答by Dagg Nabbit

String(value)should have the same result as value.toString()in every case, except for values without properties like nullor undefined. ''+valuewill produce the same result.

String(value)应该具有与value.toString()每种情况相同的结果,除了没有像nullor 等属性的值undefined''+value将产生相同的结果。

回答by Louay Alosh

String()[the constructor call] is basically calling the .toString()

String()[构造函数调用] 基本上是调用.toString()

.toString()and String()can be called on primitive values(number,boolean,string) and basically will do nothing special:

.toString()String()可以在原始值(数字,布尔值,字符串)上调用,基本上不会做任何特别的事情:

true => 'true'

false => 'false'

17 => '17'

'hello' => 'hello'

真 => '真'

假 => '假'

17 => '17'

'你好' => '你好'

Butcalling these functions on objects is where things gets interesting:

但是在对象上调用这些函数是事情变得有趣的地方:

if the object has it's own .toString() function it will be called when ever you need this object to be treated as a string(explicitly/implicitly)

如果对象有它自己的 .toString() 函数,当您需要将此对象视为字符串时,它将被调用(显式/隐式)

let obj = {
           myName:"some object",
           toString:function(){ return this.myName; } 
          }

//implicitly treating this obj as a string
"hello " + obj; //"hello some object"

//OR (explicitly)
"hello " + String(obj) //calling the existent toString function

//OR
"hello " + obj.toString(); //calling toString directly

By the way if you want to treat this object as a number it should has a .valueOf()function defined in it.

顺便说一下,如果你想把这个对象当作一个数字,它应该有一个.valueOf()函数定义在它里面。

what if we have both in one object?

if we want to treat this object as a string => use .toString()

if we want to treat this object as a number => use .valueOf()

如果我们在一个对象中同时拥有两者呢?

如果我们想将此对象视为字符串 => 使用.toString()

如果我们想将此对象视为数字 => 使用.valueOf()

what if we only have .valueOf()defined?

如果我们只定义了.valueOf()呢?

.valueOf()defined inside the object will be called whether we want to handle the object as a string or as a number

无论我们想将对象作为字符串还是数字处理,都将调用对象内部定义的.valueOf()