Why Symbols not convert string implicitly

2020-03-01 08:22发布

Why Symbol('test').toString() works well, but I can't use '' + Symbol('test')?

It will throw Error:

cannot convert a Symbol value to a string

Why does the implicit type conversion not work? Why is the code not equal to '' + Symbol('test').toString()?

标签: javascript
3条回答
够拽才男人
2楼-- · 2020-03-01 08:58

According to ECMA-262, using the addition operator on a value of type Symbol in combination with a string value first calls the internal ToPrimitive, which returns the symbol. It then calls the internal ToString which, for Symbols, will throw a TypeError exception.

So calling the internal ToString is not the same as calling Symbol.prototype.toString.

So I guess the answer to:

Why does the implicit type conversion not work?

is "because the spec says so".

查看更多
家丑人穷心不美
3楼-- · 2020-03-01 09:10

your type not string

'' + Symbol('test').toString()

you can check, Symbol is a new type in ES6

https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol

The Symbol() function returns a value of type symbol, .....
查看更多
可以哭但决不认输i
4楼-- · 2020-03-01 09:14

You can, your just not meant to do it by accident.

console.log(''+String(Symbol('My symbol!')))
// Symbol(My other symbol!)

console.log(Symbol.keyFor(Symbol.for('My other symbol!')))
// My other symbol!    

Note: Symbol.keyFor only works for symbols created via the Symbol.for function.

Symbol.keyFor(Symbol('My symbol!')) will evaluate to undefined.

查看更多
登录 后发表回答