About setTimeout/Interval context

风格不统一 提交于 2019-12-08 14:09:30

问题


Why I can't do this:

function f(){console.log(this)}
f.call(this);
setInterval(f.call, 1000, this);

回答1:


You should use .bind instead of .call:

function f(){console.log(this)}
setInterval(f.bind(the_context_obj), 1000);



回答2:


Try this:

setInterval(f.call.bind(f, this), 1000);

http://jsfiddle.net/Qx3jU/

It's just a bad way of saying setInterval(f.bind(this), 1000); though




回答3:


Because you are passing the value of f.call so you lose the association with f.




回答4:


From Mozilla Dev page

Syntax is :

var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var intervalID = window.setInterval(code, delay);

Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer. If you want to enable this functionality on that browser you must use a compatibility code (see the Callback arguments paragraph).

Then I'll recommend you to use an anonymous function like this

var x = this;
setInterval( function() { f.call(x); }, 1000 ); 

Hope this helps.



来源:https://stackoverflow.com/questions/11931612/about-settimeout-interval-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!