Closed Bug 824376 Opened 12 years ago Closed 12 years ago

Cannot use Iterator from the Addon SDK

Categories

(Add-on SDK Graveyard :: General, defect)

x86_64
Linux
defect
Not set
normal

Tracking

(Not tracked)

RESOLVED WONTFIX

People

(Reporter: protz, Unassigned)

Details

https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Iterators_and_Generators

The "Iterator" constructor is not defined, I'm getting "ReferenceError: Iterator is not defined". Is this intentional? It seems I can use many other Javascript 1.8 constructions (which is cool!).
Hi Jonathan,

Yes `Iterator` is intentionally not present, mainly because it's was problematic to make our APIs compatible with it. It's should not be a big issues though, since spidermonkey already implements standard alternative in form of `for of`, see mdn
link for details:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...of

MDN does not seems to note that `for of` can be used to iterate over key value pairs
but you can see example of that here:
https://github.com/mozilla/addon-sdk/blob/master/lib/sdk/context-menu.js#L1039

Finally if you just wish to copy paste code that depends on `Iterator` it's still very easy to implement `Iterator` to make that work too:

function Iterator(dictionary) {
  return {
    __iterator__: function() {
      for (let key in dictionary) yield [key, dictionary[key]
    }
  }
}

Hope this help ;)
Status: NEW → RESOLVED
Closed: 12 years ago
Resolution: --- → WONTFIX
Alright, that seems like a very sensible thing to do, since indeed the for of construct is now present. I got used to Iterator from the times where for of was not implemented, but now I see no reason why I shouldn't switch to it.

Thanks for the detailed explanation! :)

Cheers,

jonathan
I also just stumbled across this issue and would like to note the following details that might help others:

 * for...of can't be used with plain Objects, like `{ name: value }`, only with primitives that are iterable: Array, Map, Set, etc.
 * The `Iterator` shim that Irakli posted didn't work for me, but using a Generator did work:

```js
function Iterator(obj) {
  for (let key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key))
      yield [key, obj[key]];
  }
}
```

This made me very happy, in the end, I hope it will do the same for you :)
You need to log in before you can comment on or make changes to this bug.