2 回答

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
與Python之類的語(yǔ)言不同,Javascript方法會(huì)在您將其提取并將其傳遞到其他位置后忘記它。你也可以
將方法調(diào)用包裝在匿名函數(shù)中
這樣,訪問(wèn)baz屬性并同時(shí)調(diào)用它,這是this在方法調(diào)用中正確設(shè)置所必需的。
您需要this將外部函數(shù)保存在輔助變量中,因?yàn)閮?nèi)部函數(shù)將引用另一個(gè)this對(duì)象。
var that = this;
setInterval(function(){
return that.baz();
}, 1000);
將方法調(diào)用包含在胖箭頭函數(shù)中
在實(shí)現(xiàn)箭頭函數(shù)功能的Javascript實(shí)現(xiàn)中,可以使用胖箭頭語(yǔ)法以更簡(jiǎn)潔的方式編寫上述解決方案:
setInterval( () => this.baz(), 1000 );
胖箭頭匿名函數(shù)保留了this周圍的函數(shù),因此不需要使用該var that = this技巧。要查看是否可以使用此功能,請(qǐng)參閱此類兼容性表。
使用綁定功能
最后一種方法是使用Function.prototype.bind等函數(shù)或您喜歡的Javascript庫(kù)中的等效函數(shù)。
setInterval( this.baz.bind(this), 1000 );
//dojo toolkit example:
setInterval( dojo.hitch(this, 'baz'), 100);

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
我做了一個(gè)代理類:)
function callback_proxy(obj, obj_method_name)
{
instance_id = callback_proxy.instance_id++;
callback_proxy.instances[instance_id] = obj;
return eval('fn = function() { callback_proxy.instances['+instance_id+'].'+obj_method_name+'(); }');
}
callback_proxy.instance_id = 0;
callback_proxy.instances = new Array();
function Timer(left_time)
{
this.left_time = left_time; //second
this.timer_id;
this.update = function()
{
this.left_time -= 1;
if( this.left_time<=0 )
{
alert('fin!');
clearInterval(this.timer_id);
return;
}
}
this.timer_id = setInterval(callback_proxy(this, 'update'), 1000);
}
new Timer(10);
添加回答
舉報(bào)