var progressbar = {
progress : null,
html : function() {
var loadingHtml = '<div id="loader-wrapper" class="catalog-loadmore">';
loadingHtml += '<div class="progress"><div id="catalog-bar" class="progress-bar progress-bar-striped active" style="width: 10%"></div></div>';
loadingHtml += '<div class=""><span id="progress-valuenow"></span>%</div>';
loadingHtml += '</div>';
return loadingHtml
},
start : function() {
var width = 10;
this.progress = setInterval(function() {
$('#catalog-bar').css('width', width + '%');
$('#progress-valuenow').text(width);
if(width < 98){
width += 1;
}else{
this.stop(); // this is not working
clearInterval(this.progress); // this is also not working
console.log('else')
}
}, 100);
},
stop : function() {
clearInterval(this.progress);
},
destroy : function() {
clearInterval(this.progress);
$('#loader-wrapper').remove();
}
}
在上面的代码中,为什么下面的语句不起作用,否则执行else条件console.log('else')
是打印但clearInterval()不起作用。我从外面打电话给progressbar.destroy(),它正在工作。
this.stop(); // this is not working
clearInterval(this.progress); // this is also not working
谁能告诉我我做错了什么。
您已经将匿名函数传入了setInterval
,匿名函数的上下文已this
设置为window
,因此您的目标是window.progress
。
您有两种方法可以解决问题:
存储this
在一些变量中 var _this = this; setInterval(function() { ... clearInterval(_this.progress) } ...)
用于Function.prototype.bind()
设置匿名函数的上下文,例如 setInterval(function() { ... clearInterval(this.progress) }.bind(this) ...)
或为ES6设置transpiler并使用自动Arrow function
绑定this
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句