String(value)与value.toString()之间的区别是什么 [英] What's the difference between String(value) vs value.toString()
问题描述
Javascript在类型和类型转换方面有很多技巧,所以我想知道这两种方法是否相同,或者是否存在一些使它们不同的极端情况?
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?
推荐答案
它们并不完全相同,实际上,作为函数调用的String构造函数(你的第一个例子),最后会调用传递的对象的 toString
方法,例如:
They are not completely the same, and actually, the String constructor called as a function (your first example), will at the end, call the toString
method of the object passed, for example:
var o = { toString: function () { return "foo"; } };
String(o); // "foo"
另一方面,如果标识符引用 null
或 undefined
,你不能使用 toString
方法,它会给你a TypeError
异常:
On the other hand, if an identifier refers to null
or undefined
, you can't use the toString
method, it will give you a TypeError
exception:
var value = null;
String(null); // "null"
value.toString(); // TypeError
String
构造函数被调用为函数大致相当于:
The String
constructor called as a function would be roughly equivalent to:
value + '';
Object -to- Primitive <的类型转换规则/ em>详细描述了规范, [ [DefaultValue]]
内部操作。
The type conversion rules from Object-to-Primitive are detailed described on the specification, the [[DefaultValue]]
internal operation.
简要概括,从 Object转换 - 到 - String ,采取以下步骤:
Briefly summarized, when converting from Object-to-String, the following steps are taken:
- 如果可用,执行
toString
方法。
- 如果
结果
是原语,则返回结果
,否则转到步骤2.
- 如果
- If available, execute the
toString
method.- If the
result
is a primitive, returnresult
, else go to Step 2.
- If the
- 如果
结果
是原语,则返回结果
,否则转到步骤3.
- If the
result
is a primitive, returnresult
, else go to Step 3.
鉴于上述规则,我们可以举例说明所涉及的语义:
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
}
如果您想了解更多有关此机制的信息,我建议您查看在 ToPrimitive
和 ToString
内部操作。
If you want to know more about this mechanism I would recommend looking at the ToPrimitive
and the ToString
internal operations.
我还建议阅读这篇文章:
I also recommend reading this article:
- Object-to-Primitive Conversions in JavaScript
这篇关于String(value)与value.toString()之间的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!