Search code examples
javascriptcallsettimeout

About setTimeout/Interval context


Why I can't do this:

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

Solution

  • You should use .bind instead of .call:

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