符号:隐式字符串转换在JavaScript中如何工作? [英] Symbols: How does implicit string conversion work in JavaScript?
问题描述
阅读JavaScript中Symbol
的文档,并在一些环境(Chrome,Firefox,Node.js)中进行测试,我意识到我对隐式字符串转换的理解是有缺陷的.
Reading the documentation on Symbol
s 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.
我总是给人一种印象,尝试转换为字符串时会调用对象的toString()
方法,如果该函数未返回原语,则它将调用对象的toPrimitive()
方法,如果不起作用,它将输入错误.但是,此说明未能涵盖Symbol
抛出的TypeError
:
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 Symbol
s throw:
var sym = Symbol("test");
try {
console.log(sym + "ing");
} catch (error) {
console.error(error);
}
TypeError: Cannot convert a Symbol value to a string
但是很明显Symbol
具有有效的toString()
方法.那么为什么不叫它呢?
But it's apparent that Symbol
s have a valid toString()
method. So why isn't it called?
推荐答案
您正确的是,在进行隐式字符串转换时将调用对象toString
方法.但是,如规范所述,符号上的隐式字符串转换会导致TypeError
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
.
鉴于字符串和符号都可以是属性键,因此您希望保护人们免于意外将符号转换为字符串.
Given that both strings and symbols can be property keys, you want to protect people from accidentally converting a symbol to a string.
这篇关于符号:隐式字符串转换在JavaScript中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!