我想做这样的事情:
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); } // <-- 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)');
请注意,我将变量 , 设置self为this,然后Function#call在调用时使用end,这允许我们在调用期间设置特定值this。这是有效的,因为传递给的匿名函数setTimeout具有对创建它的执行上下文以及其中的所有变量的引用,因此可以访问self(and a)。
如果没有一个很好的使用理由eval(而且我在这里没有看到),我不会这样做:
function end(){ console.log(this); }
var a = 0, self = this; setTimeout(function(){ a = 10; end.call(self); }, 2000);
您还可以创建第二个函数,该函数在调用时会转身并end以正确的this值调用。这称为绑定,由 ES5Function#bind函数促进:
function end(){ console.log(this); }
var a = 0, boundEnd = end.bind(this); setTimeout(function(){ a = 10; boundEnd(); }, 2000);
由于您使用的是 NodeJS,因此您使用的是 V8,它具有Function#bind. bind(如果您在浏览器中执行此操作,如果您需要支持旧版浏览器,则必须小心提供 shim 。)