String.prototype.toString()
Try it
语法
参数
返回值
描述
¥Description
String
对象重写了 Object
的 toString
方法;它不继承 Object.prototype.toString()
。对于 String
值,toString
方法返回字符串本身(如果它是基元)或 String
对象封装的字符串。它具有与 String.prototype.valueOf()
完全相同的实现。
¥The String
object overrides the toString
method of Object
; it does not inherit
Object.prototype.toString()
. For String
values, the toString
method returns the string itself (if it's a primitive) or the string that the String
object wraps. It has the exact same implementation as String.prototype.valueOf()
.
toString()
方法要求其 this
值是 String
基元或封装对象。它为其他 this
值抛出 TypeError
,而不尝试将它们强制为字符串值。
¥The toString()
method requires its this
value to be a String
primitive or wrapper object. It throws a TypeError
for other this
values without attempting to coerce them to string values.
由于 String
没有 [Symbol.toPrimitive]()
方法,因此当在需要字符串的上下文中(例如在 模板文字 中)使用 String
对象时,JavaScript 会自动调用 toString()
方法。但是,String 基元值不会将 toString()
方法咨询为 强制为字符串 — 因为它们已经是字符串,因此不执行任何转换。
¥Because String
doesn't have a [Symbol.toPrimitive]()
method, JavaScript calls the toString()
method automatically when a String
object is used in a context expecting a string, such as in a template literal. However, String primitive values do not consult the toString()
method to be coerced to strings — since they are already strings, no conversion is performed.
String.prototype.toString = () => "Overridden";
console.log(`${"foo"}`); // "foo"
console.log(`${new String("foo")}`); // "Overridden"
示例
使用 toString()
规范
Specification |
---|
ECMAScript Language Specification # sec-string.prototype.tostring |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also