符号:隐式字符串转换在JavaScript中如何工作? [英] Symbols: How does implicit string conversion work in JavaScript?

查看:58
本文介绍了符号:隐式字符串转换在JavaScript中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读JavaScript中Symbol的文档,并在一些环境(Chrome,Firefox,Node.js)中进行测试,我意识到我对隐式字符串转换的理解是有缺陷的.

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.

我总是给人一种印象,尝试转换为字符串时会调用对象的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 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

但是很明显Symbol具有有效的toString()方法.那么为什么不叫它呢?

But it's apparent that Symbols 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.

博士. Axel Rauschmayer说了:

鉴于字符串和符号都可以是属性键,因此您希望保护人们免于意外将符号转换为字符串.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆