为什么符号不能隐式转换字符串 [英] Why Symbols not convert string implicitly
问题描述
为什么 Symbol('test').toString()
效果很好,但是我不能使用''+ Symbol('test')
?
Why Symbol('test').toString()
works well, but I can't use '' + Symbol('test')
?
它将抛出错误:
无法将符号值转换为字符串
cannot convert a Symbol value to a string
为什么隐式类型转换不起作用?为什么代码不等于''+ Symbol('test').toString()
?
Why does the implicit type conversion not work? Why is the code not equal to '' + Symbol('test').toString()
?
推荐答案
根据ECMA-262,使用 ToPrimitive ,该符号将返回.然后,它会调用内部 ToString ,对于Symbols,它将抛出TypeError异常.
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.
所以我想答案是
为什么隐式类型转换不起作用?
Why does the implicit type conversion not work?
是"因为规范是这样".
这篇关于为什么符号不能隐式转换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!