symbol.toString
symbol.toString
toString()
方法返回当前 symbol 对象的字符串表示。
语法
Symbol().toString(
返回值
代表指定Symbol
对象的字符串。
描述
Symbol
对象拥有自己的toString
方法,因而遮蔽了原型链上的Object.prototype.toString()
。
symbol 原始值不能转换为字符串
symbol 原始值不能转换为字符串,所以只能先转换成它的包装对象,再调用 toString() 方法:
Symbol('foo') + 'bar'; // TypeError: Can't convert symbol to string
示例
Symbol('desc').toString( // "Symbol(desc)"
// well-known symbols
Symbol.iterator.toString( // "Symbol(Symbol.iterator)
// global symbols
Symbol.for('foo').toString() // "Symbol(foo)"
规范
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Symbol.prototype.toString' in that specification. | Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262)The definition of 'Symbol.prototype.toString' in that specification. | Draft | |
浏览器兼容性
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | 36.0 (36.0) | No support | No support | No support |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | 36.0 (36.0) | No support | No support | No support |