Symbols: How does implicit string conversion work

2020-07-08 06:27发布

Reading the documentation on Symbols in JavaScript, and also testing in a few environments (Chrome, Firefox, Node.js), I've realized that my understanding of implicit string conversion is flawed.

I was always under the impression that the object's toString() method was called when attempting to convert to a string, and if that function didn't return a primitive, then it called the object's toPrimitive() method, then if that didn't work it would type-error. However, this explanation fails to cover the TypeError that Symbols throw:

var sym = Symbol("test");

try {
  console.log(sym + "ing");
} catch (error) {
  console.error(error);
}

TypeError: Cannot convert a Symbol value to a string

But it's apparent that Symbols have a valid toString() method. So why isn't it called?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2020-07-08 07:20

You're right that an objects toString method is called when doing implicit string conversions. However, as the spec states, implicit string conversions on symbols cause a TypeError.

As Dr. Axel Rauschmayer put it:

Given that both strings and symbols can be property keys, you want to protect people from accidentally converting a symbol to a string.

查看更多
登录 后发表回答