I cannot seem to create a generator method as object literal.
Here is my working source code:
function *getRecords (data) {
for (var i = 0; i < data.length; i++) {
yield data[i];
}
}
var records = getRecords(data);
for (var record of records) {
// process my record
}
But the when I move my generator method in object literal:
var myobj = {
*getRecords: function (data) {...}
}
I get SyntaxError: Unexpected token *
If I add quotes
var myobj = {
'*getRecords': function (data) {...}
}
I get: SyntaxError: Unexpected strict mode reserved word
I'm runnng nodejs v0.12.2 with --harmony
option, but no matter what I do, I can't seem to get it working.
The function* declaration ( function keyword followed by an asterisk) defines a generator function, which returns a Generator object.
JavaScript methods are actions that can be performed on objects. A JavaScript method is a property containing a function definition. Methods are functions stored as object properties.
Declaring methods and properties using Object Literal syntax The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array.
In a normal function, there is only one entry point: the invocation of the function itself. A generator allows you to pause the execution of a function and resume it later. Generators are useful when dealing with iterators and can simplify the asynchronous nature of Javascript.
A @thefoureye already answered, if you are using function expressions then you will have to place the *
token right after the function
token.
However, you can also use method definitions in object literals. Here, you'd place the *
before the generator method name indeed, however as with every method definition it does not contain the colon and the function
keyword:
var myobj = {
*getRecords(data) {
…
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With