这个javascript生成器的价值

时间:2013-07-21 13:52:52

标签: javascript generator ecmascript-6

javascript中javascript生成器中this的值是多少? 在下面的代码中,两个比较都返回false,当我执行.toSource()时,this似乎是空的Object。参考ECMA或MDN文档会有所帮助,我无法找到任何内容。

function thisGenerator(){
    while(1)
        yield this;
}

var gen=new thisGenerator();
alert(gen.next()==thisGenerator);
alert(gen.next()==gen);

1 个答案:

答案 0 :(得分:1)

this仍遵守正常规则。 考虑到,全球范围是window

var gen = (function() { yield this; })(); gen.next() === window // true
var gen = (function() { "use strict"; yield this; })(); gen.next() === undefined // true

在怪癖模式下,未绑定函数中的this将是全局范围(恰好是window),而在严格模式下,它是undefined

PS:当调用绑定的函数时,一切都仍然正常:

var o = { foo: function() { yield this; } }; o.foo().next() === o // true
var o = {}; function foo() { yield this; }; foo.call(o).next() === o // true