Javascript:返回在eval中创build的值
我想要做这样的事情:
function end(){ console.log(this); } // <-- the problem is here with `this` eval('var a = 0; setTimeout(function(){ a = 10; end(); }, 2000)');
2秒后应输出:
{ "a" : 10 }
这有可能吗?
是:
function end(){ console.log(this); } eval('var a = 0, self = this; setTimeout(function(){ a = 10; end.call(self); }, 2000)');
请注意,我将variablesself
设置为this
,然后在调用end
时使用Function#call
,这允许我们在调用期间this
设置特定的值。 这是有效的,因为传递给setTimeout
的匿名函数有一个对创build它的执行上下文的引用以及其中的所有variables,因此可以访问self
(和a
)。
如果使用eval
没有很好的理由 (我在这里没有看到),我不会这样做:
function end(){ console.log(this); } var a = 0, self = this; setTimeout(function(){ a = 10; end.call(self); }, 2000);
你也可以创build第二个函数,当被调用的时候,它会转过来,并且调用以this
值end
。 这被称为绑定 ,并通过ES5 Function#bind
函数来实现 :
function end(){ console.log(this); } var a = 0, boundEnd = end.bind(this); setTimeout(function(){ a = 10; boundEnd(); }, 2000);
由于您使用的是NodeJS,因此您使用的是具有Function#bind
V8。 (如果你是在浏览器中这样做的话,如果你需要支持旧浏览器的话,你必须小心地提供一个bind
的垫片。)