最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ES 6: Difference between Symbol.iterator and @@iterator - Stack Overflow

programmeradmin2浏览0评论

I was wondering if there was a specific difference in implementing an iterator using the @@iterator function versus the Symbol.iterator one:

On MDN, there is a page on Array.prototype.@@iterator, yet in the examples itself, Symbol.iterator is used as the function name. Is this just the updated version and @@iterator is not valid anymore, or are both of them valid?

I was wondering if there was a specific difference in implementing an iterator using the @@iterator function versus the Symbol.iterator one:

On MDN, there is a page on Array.prototype.@@iterator, yet in the examples itself, Symbol.iterator is used as the function name. Is this just the updated version and @@iterator is not valid anymore, or are both of them valid?

Share Improve this question asked Apr 16, 2015 at 9:16 nilsnils 27.2k6 gold badges73 silver badges81 bronze badges 1
  • 1 This may help: stackoverflow.com/q/29492333/218196 – Felix Kling Commented Apr 16, 2015 at 9:25
Add a comment  | 

2 Answers 2

Reset to default 12

There is no @@iterator function. That token produces a syntax error - it is only used in specification to denote a specific symbol.

If you want to use that symbol in your code, e.g. to access iterators on arrays, you have to use Symbol.iterator. Which is a property of the Symbol class initialised to have the value @@iterator.

The ECMAScript 2015 (ES6) specification uses @@iterator to reference Symbol.iterator. There is no @@iterator, and wherever you see it, read it as Symbol.iterator.

I think (someone more familiar with the ECMAScript spec might be able to back this up) the reason @@iterator is used is because you need to access Symbol properties on an object using square brackets ([]), but most parts of the ES2015 specification (and documentation) used the more familiar dot-notion (e.g. object.property versus object["property"]), and so@@somesymbol` is used to keep things consistent.

See page 38 (marked as page 18): http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

发布评论

评论列表(0)

  1. 暂无评论