Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

javascript - What is the point of the 'Symbol' type in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...