Reputation: 6470
Why is the function working only once in the below code ?
(function ( $ ) {
$.fn.test = function() {
setInterval(hi.call(this), 1000);
function hi(){
console.log(this);
}
};
}( jQuery ));
$('div').test();
Upvotes: 0
Views: 62
Reputation: 318182
call()
calls the function with a this-value and optional arguments, it would be the same as
setInterval(hi(), 1000);
and as that function doesn't return anything, it's the same as
var x = hi(); // undefined
setInterval(x, 1000);
// ^ still undefined
What you wanted was to create a new function with a given this-value using bind()
setInterval(hi.bind(this), 1000);
A little more jQuery'ish using $.proxy
setInterval( $.proxy(hi, this), 1000);
Upvotes: 3