ECMA-262-V6中“符号”类型的要点是什么? [英] What is the point of the 'Symbol' type in ECMA-262-v6?

查看:189
本文介绍了ECMA-262-V6中“符号”类型的要点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ECMA-262-v6中符号类型的要点是什么?快速路径实现对象键?它在引擎盖下做什么 - 哈希它保证底层数据是不可变的?

What is the point of the 'Symbol' type in ECMA-262-v6? Fast path implementation for object keys? What does it do under the hood - hash it with the guarantee that the underlying data is immutable?

推荐答案

符号是私钥取代魔术名字。它们阻止使用简单的字符串来引用该字段,因此只有具有符号的消费者才能访问。

Symbols are private keys that replace magic names. They prevent using a simple string to reference the field, so only consumers with the symbol can gain access.

某些符号用于表示运行时的特定行为(如 Symbol.iterator ,其行为非常像预先共享的秘密),而其他可以由库分配,并用于有效地隐藏字段。

Some symbols are used to indicate particular behaviors to the runtime (like Symbol.iterator, which acts much like a pre-shared secret), while others can be allocated by the library and used to effectively hide fields.

通常,符号旨在替代魔术名称。您可以分配一个符号 const foo = Symbol()而不是具有简单称为foo的属性,而是有选择地传递。这允许运行时在启动时分配 Symbol.iterator ,并确保任何尝试实现迭代的人都能以一致的方式进行。

In general, symbols are intended as a replacement for magical names. Rather than having a properties simply called 'foo', you can allocate a symbol const foo = Symbol() and pass that selectively. This allows the runtime to allocate Symbol.iterator when it starts up and guarantees that anyone trying to implement an iterable does so in a consistent fashion.

运行时可以使用符号来优化对某些字段的访问,如果它感觉到需要但不必。

The runtime could use symbols to optimize access to certain fields, if it felt the need to, but doesn't have to.

根据使用情况,您可以使用符号将消费者引导到特定的方法。例如,如果您有一个可以返回同步迭代或生成器的库,具体取决于客户端的异步支持,您可以:

You can use symbols to direct consumers to a particular method, depending on their usage. For example, if you had a library that could return a synchronous iterable or a generator, depending on the client's async support, you could:

const syncIterable = Symbol();
const asyncIterable = Symbol();

class Foo {
  static getIterable(async = false) {
    return async ? asyncIterable : syncIterable;
  }

  [syncIterable]() {
    return new SyncFoo();
  }

  [asyncIterable]() {
    return new AsyncFoo();
  }
}

let foo = new Foo();
for (let x of foo[Foo.getIterable(true)]()) {
  // could be a iterator, could be a generator
}

这是一个相当有创意的例子,但显示了图书馆如何使用符号来选择性地提供对用户的访问。

That's a rather contrived example, but shows how a library can use symbols to selectively provide access to users.

这篇关于ECMA-262-V6中“符号”类型的要点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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