progressbar原型中的JavaScript事件处理程序提供了未定义的值
我目前正在构建一个JavaScript对象,该对象创建一个进度条,并允许在某些元素上使用单击侦听器增加进度条值。progressbar原型中的JavaScript事件处理程序提供了未定义的值,javascript,jquery,oop,nan,Javascript,Jquery,Oop,Nan,我目前正在构建一个JavaScript对象,该对象创建一个进度条,并允许在某些元素上使用单击侦听器增加进度条值。 我遇到了一个问题,当我点击一个应该增加当前值的按钮时,当我向窗口提示该值时,它会说该值为NaN,我不知道为什么 这是我的密码: //Progress Bar var ProgressBar = function(element, startVal, endVal, step, addLefts, addRights) { this.element = element;
我遇到了一个问题,当我点击一个应该增加当前值的按钮时,当我向窗口提示该值时,它会说该值为NaN,我不知道为什么 这是我的密码:
//Progress Bar
var ProgressBar = function(element, startVal, endVal, step, addLefts, addRights) {
this.element = element;
this.endVal = endVal;
this.currentVal = startVal;
this.step = step;
this.addLefts = addLefts;
this.addRights = addRights;
var self = this;
}
ProgressBar.prototype.initializeProgressBar = function() {
jQuery(this.element).progressbar({
value : this.currentVal
});
for(var i = 0; i < this.addLefts.length; i++) {
this.addLefts[i].addEventListener("click", this.removeAmount, false);
}
for(var i = 0; i < this.addRights.length; i++) {
this.addRights[i].addEventListener("click", this.addAmount, false);
}
}
ProgressBar.prototype.addAmount = function() {
this.currentVal += this.step;
alert(this.currentVal);
}
ProgressBar.prototype.removeAmount = function() {
this.currentVal -= this.step;
alert(this.currentVal);
}
为什么'this.currentVal'属性从
addAmount
和removeAmount
函数中返回NaN?您需要将this绑定到函数
this.addRights[i].addEventListener("click", this.addAmount.bind(this), false);
如果您使用下划线之类的符号,您可以做一些更棘手的事情,请使用一个:-
ProgressBar.prototype.change = function(sign) {
this.currentVal += (this.step * sign);
}
然后:-
this.addLefts[i].addEventListener("click", _.partial(this.change,-1).bind(this), false);
this.addRights[i].addEventListener("click", _.partial(this.change, 1).bind(this), false);
您需要将此绑定到您的函数
this.addRights[i].addEventListener("click", this.addAmount.bind(this), false);
如果您使用下划线之类的符号,您可以做一些更棘手的事情,请使用一个:-
ProgressBar.prototype.change = function(sign) {
this.currentVal += (this.step * sign);
}
然后:-
this.addLefts[i].addEventListener("click", _.partial(this.change,-1).bind(this), false);
this.addRights[i].addEventListener("click", _.partial(this.change, 1).bind(this), false);
当您添加
this.addAmount
或this.removeAmount
作为事件处理程序时,它将在元素的上下文中调用,而不是在ProgressBar
实例中调用
要解决这个问题,可以使用bind()
强制在正确的上下文中调用它
for(var i = 0; i < this.addLefts.length; i++) {
this.addLefts[i].addEventListener("click", this.removeAmount.bind(this), false);
}
for(var i=0;i
当您添加this.addAmount
或this.removeMount
作为事件处理程序时,它将在元素的上下文中调用,而不是在ProgressBar
实例中调用
要解决这个问题,可以使用bind()
强制在正确的上下文中调用它
for(var i = 0; i < this.addLefts.length; i++) {
this.addLefts[i].addEventListener("click", this.removeAmount.bind(this), false);
}
for(var i=0;i
这意味着是this.currentVal+=this.step
或this.currentVal-=this.step
引起问题。。在操作前检查this.currentVal
和this.step
的值和类型您将丢失“this”。放一个console.log(这个);在函数的开头…这意味着是this.currentVal+=this.step
或this.currentVal-=this.step
引起问题。。在操作前检查this.currentVal
和this.step
的值和类型您将丢失“this”。放一个console.log(这个);在函数的开头。。。