Symbol toStringTag Customizes Object toString

The [object X] label from Object.prototype.toString reads Symbol.toStringTag, so custom classes can brand their diagnostics without touching instanceof.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
class Money {
  constructor(cents) {
    this.cents = cents;
  }
  // Object.prototype.toString 读取 Symbol.toStringTag 作为标签名
  get [Symbol.toStringTag]() {
    return 'Money';
  }
}

const price = new Money(1999);

// 默认标签是 Object;自定义后变成 [object Money]
console.log(String(Object.prototype.toString.call({})));
console.log(String(Object.prototype.toString.call(price)));

// Map/Set/Date 等内建类型靠同一机制报出自己的名字
console.log(String(Object.prototype.toString.call(new Map())));

// instanceof 不受影响:toStringTag 只改 toString 的输出
console.log('instanceof still works:', price instanceof Money);
console.log('tag:', price[Symbol.toStringTag]);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

[object Object]
[object Money]
[object Map]
instanceof still works: true
tag: Money

The tag mechanism

Object.prototype.toString reads Symbol.toStringTag when producing [object X]. The Money class defines a getter returning ‘Money’, so toString.call(price) prints [object Money] instead of the default [object Object] shown for the plain {} line.

Built-ins use it too

The Map line prints [object Map] because built-ins carry the same well-known symbol — the demo grounds the mechanism in both custom and built-in classes.

instanceof untouched

The tag only changes toString output: price instanceof Money still prints true, and reading price[Symbol.toStringTag] returns the string the getter produces.

Interactive Tools for This Topic

FAQ

Does defining Symbol.toStringTag affect instanceof?
No. instanceof walks the prototype chain; the tag only changes what Object.prototype.toString prints.
Why does a plain object print [object Object]?
It has no Symbol.toStringTag, so the default tag Object is used — the demo contrasts this with the Money and Map results.