Is there a way to specify an ES6 generator method in an object literal in node.js?

I cannot create a generator method as an 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 when I transfer my generator method to the 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 am running nodejs v0.12.2 with the --harmony , but no matter what I do, I cannot get it to work.

+7
source share
3 answers

* must be after the function keyword, e.g.

 var myobj = { getRecords: function* (data) {} } for (var record of myobj['getRecords']()) {} 

Quoting a draft version of ECMA Script - 6 for Expression Generator ,

function * (FormalParameters [Yield, GeneratorParameter] ) {

<i> GeneratorBody

}

Note. The expression of the generator is different from the function of the generator. When you assign it to a variable or bind it to a key in an object literal, you are actually assigning a generator expression. A normal generator declaration will look like this:

 function * GeneratorFunctionName(...) { } 
+7
source

A @thefoureye already answered, if you use function expressions, then you will need to put the token * right after the function token.

However, you can also use method definitions in object literals. Here you put * before the name of the generator method, but, like with every method definition, it does not contain the colon keyword and function :

 var myobj = { *getRecords(data) { … } }; 
+9
source

Here's how to do it in the definition of a simple object:

 var myobj = { getRecords: function* (data) {...} } 

Here's how to do it in the ES6 class definition:

 class MyClass { * getRecords(data) {...} } var myobj = new MyClass(); 
+2
source

Source: https://habr.com/ru/post/985527/


All Articles