有没有办法在node.js中的对象文字中指定ES6生成器方法? [英] Is there a way to specify ES6 generator method in object literal in node.js?
问题描述
这是我的工作源代码:
function * getRecords(data){
for(var i = 0; i< data.length; i ++){
yield data [i]
}
}
var records = getRecords(data);
(var record of records){
//处理我的记录
}
但是当我将生成器方法移动到对象文字中时:
var myobj = {
* getRecords:function(data){...}
}
我得到 SyntaxError:Unexpected token *
如果我添加引号
var myobj = {
'* getRecords':function(data){...}
}
我得到: SyntaxError:意外严格模式保留字
我是runnng nodejs v0.12.2与 - 和谐
选项,但无论我做什么,我似乎无法使其工作。
*
应该在函数后面c $ c>关键字,像这样
var myobj = {
getRecords:function *(data){}
}
for(var record of myobj ['getRecords']()){}引用 ECMA脚本草案版本 - 6生成器表达式的定义,
function *(FormalParameters [Yield,GeneratorParameter] ){
GeneratorBody p>
}
注意:生成器表达式不同来自发电机功能。当您将其分配给变量或将其与对象文字中的键相关联时,实际上分配了生成器表达式。正常的生成器声明将如下
function * GeneratorFunctionName(...){
}
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 *
should be after the function
keyword, like this
var myobj = {
getRecords: function* (data) {}
}
for (var record of myobj['getRecords']()) {}
Quoting the Draft version of ECMA Script - 6's definition for Generator Expression,
function * ( FormalParameters[Yield,GeneratorParameter] ) {
GeneratorBody
}
Note: Generator Expression is different from Generator Function. When you assign it to a variable or associate it to a key in Object literal, you are actually assigning a Generator Expression. The normal generator declaration will be like this
function * GeneratorFunctionName(...) {
}
这篇关于有没有办法在node.js中的对象文字中指定ES6生成器方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!