Symbol.toStringTag
well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the
Object.prototype.toString()
方法。
特性属性在
Symbol.toStringTag
|
|
|---|---|
| 可写 | no |
| 可枚举 | no |
| 可配置 | no |
Object.prototype.toString.call('foo'); // "[object String]"
Object.prototype.toString.call([1, 2]); // "[object Array]"
Object.prototype.toString.call(3); // "[object Number]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"
// ... and more
Object.prototype.toString.call(new Map()); // "[object Map]"
Object.prototype.toString.call(function* () {}); // "[object GeneratorFunction]"
Object.prototype.toString.call(Promise.resolve()); // "[object Promise]"
// ... and more
When creating your own class, JavaScript defaults to the "Object" tag:
class ValidatorClass {}
Object.prototype.toString.call(new ValidatorClass()); // "[object Object]"
Now, with the help of
toStringTag
, you are able to set your own custom tag:
class ValidatorClass {
get [Symbol.toStringTag]() {
return 'Validator';
}
}
Object.prototype.toString.call(new ValidatorClass()); // "[object Validator]"
Due to a
WebIDL spec change
in mid-2020, browsers are adding a
Symbol.toStringTag
property to all DOM prototype objects. For example, to acccess the
Symbol.toStringTag
property on
HTMLButtonElement
:
let test = document.createElement('button');
test.toString(); // Returns [object HTMLButtonElement]
test[Symbol.toStringTag]; // Returns HTMLButtonElement
| 规范 |
|---|
|
ECMAScript (ECMA-262)
The definition of 'Symbol.toStringTag' in that specification. |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
toStringTag
|
Chrome 49 | Edge 15 | Firefox 51 | IE No | Opera 36 | Safari 10 | WebView Android 49 | Chrome Android 49 | Firefox Android 51 | Opera Android 36 | Safari iOS 10 | Samsung Internet Android 5.0 |
nodejs
6.0.0
|
toStringTag
available on all DOM prototype objects
|
Chrome 50 | Edge 79 | Firefox 78 | IE No | Opera 37 | Safari 14 | WebView Android 50 | Chrome Android 50 | Firefox Android No | Opera Android 37 | Safari iOS 14 | Samsung Internet Android 5.0 | nodejs No |
完整支持
不支持
用户必须明确启用此特征。
Symbol
Function
Object
Object.prototype.__defineGetter__()
Object.prototype.__defineSetter__()
Object.prototype.__lookupGetter__()
Object.prototype.__lookupSetter__()
Object.prototype.hasOwnProperty()
Object.prototype.isPrototypeOf()
Object.prototype.propertyIsEnumerable()
Object.prototype.toLocaleString()
Object.prototype.toSource()
Object.prototype.toString()
Object.prototype.valueOf()
Object.setPrototypeOf()