2 回答

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

TA貢獻1818條經驗 獲得超8個贊
我做了一個代理類:)
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);
添加回答
舉報