@@(“at at")在 ES6 JavaScript 中是什么意思? [英] What does @@ ("at at") mean in ES6 JavaScript?
问题描述
我注意到在 @@>很少 页面关于新的 ES6 特性,但我不知道它到底是什么意思(无论是实际的语法还是某种文档约定).而且很难用谷歌搜索.有人能解释一下吗?
I've noticed @@
used in a few pages about new ES6 features, but I don't know what exactly it means (whether it's actually syntax or just some kind of documentation convention). And it's hard to google. Can someone explain it?
推荐答案
@@
描述了所谓的众所周知的符号.(请注意,它实际上不是 JS 中的有效语法.)根据 ES6/ES20151 规范:
@@
describes what's called a well-known symbol. (Note that it isn't actually valid syntax in JS.) According to the ES6/ES20151 specification:
众所周知的符号是本规范的算法明确引用的内置符号值.它们通常用作属性的键,其值用作规范算法的扩展点.除非另有说明,众所周知的符号值由所有代码领域 (8.2) 共享.
Well-known symbols are built-in Symbol values that are explicitly referenced by algorithms of this specification. They are typically used as the keys of properties whose values serve as extension points of a specification algorithm. Unless otherwise specified, well-known symbols values are shared by all Code Realms (8.2).
代码领域指的是 JavaScript 环境的不同实例.例如,根文档的代码领域将不同于在 中运行的 JavaScript.
Code Realms refer to different instances of a JavaScript environment. For example, the Code Realm of the root document would be different to that of JavaScript running in an <iframe>
.
一个对象来自哪个代码领域很重要的一个例子是,当试图使用 instanceof
来确定一个对象是否是一个数组时(提示:如果它来自另一个框架,它将不起作用).为了避免这些类型的问题与符号一起出现,它们被共享,以便对(比如)@@toString
的引用无论对象来自哪里都可以工作.
An example of where it matter what code realm an object comes from is when trying to use instanceof
to determine whether an object is an array (hint: it won't work if it's from another frame). To avoid these kinds of issues from popping up with symbols, they are shared so that references to (say) @@toString
will work no matter where the object came from.
其中一些直接通过 Symbol
构造函数公开,例如,@@toPrimitive
公开为 Symbol.toPrimitive
.这可用于覆盖尝试将对象转换为原始值时产生的值,例如:
Some of these are exposed directly through the Symbol
constructor, for example, @@toPrimitive
is exposed as Symbol.toPrimitive
. That can be used to override the value produced when attempting to convert an object to a primitive value, for example:
let a = { [Symbol.toPrimitive]: () => 1 };
console.log(+a); // 1
console.log(a.valueOf()); // (the same object)
console.log(a.toString()); // "[object Object]"
通常,符号用于为对象提供独特的属性,不会与随机属性名称发生冲突,例如:
In general, symbols are used to provide unique properties on an object which cannot collide with a random property name, for example:
let a = Symbol();
let foo = { [a]: 1 };
foo[a]; // 1
除了从某处获取符号外,没有办法访问该值(尽管您可以通过调用Object.getOwnPropertySymbols
获取对象的所有符号,因此它们不能用于实现私有属性或方法).
There is no way to access the value except by getting the symbol from somewhere (though you can get all symbols for an object by calling Object.getOwnPropertySymbols
, so they cannot be used to implement private properties or methods).
1:请参阅此 es-discuss 主题,了解有关不同的名字.
1: See this es-discuss topic for some discussion about the different names.
这篇关于@@(“at at")在 ES6 JavaScript 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!