在 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);
最佳答案
this
仍然遵守正常规则。
考虑到,全局范围是 window
:
var gen = (function() { yield this; })(); gen.next() === window // true
var gen = (function() { "use strict"; yield this; })(); gen.next() === undefined // true
在 quirks 模式下,未绑定(bind)函数中的 this
将是全局作用域(恰好是 window
),而在严格模式下则是 undefined
.
PS:当调用绑定(bind)函数时,一切照常:
var o = { foo: function() { yield this; } }; o.foo().next() === o // true
var o = {}; function foo() { yield this; }; foo.call(o).next() === o // true
关于这个的javascript生成器值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17773044/