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();
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.