我正在尝试使用Object.prototype编写和学习,我收到的错误是this.issue
在我在另一个方法中调用它时不是函数。我做错了什么导致它通过这个Uncaught TypeError?
Javascript:
$(document).ready(function() {
var Example = function() {
this.number1 = null;
this.number2 = null;
};
Example.prototype.issue = function() {
//Logic is here...
};
Example.prototype.updateNumber = function() {
//more logic is here...
this.issue();
};
Example.prototype.updateSign = function() {
//logic here...
this.issue();
};
(function() {
var solution = new Example();
})();
});
答案 0 :(得分:1)
附加于change
的{{1}}事件的处理程序,#sign
.number
Example.prototype.newNumber = function(event) {
if (event.currentTarget.id === 'number1') {
this.number1 = parseFloat($(event.currentTarget).val());
}
else {
this.number2 = parseFloat($(event.currentTarget).val());
}
this.issue();
};
Example.prototype.newSign = function(event) {
this.sign = $(event.currentTarget).val();
this.issue();
};
引用了this
,#sign
个元素,而不是
.number
个对象
new Example
尝试使用Function.prototype.bind()
将var problem = new Example();
设置为this
:new Example()
problem
处理程序中的.change()
(function() {
var problem = new Example();
$("#sign").change(problem.newSign.bind(problem));
$(".number").change(problem.newNumber.bind(problem));
})();
jsfiddle https://jsfiddle.net/czLtc82y/1/
或者,使用$.proxy()
(function() {
var problem = new Example();
$("#sign").change($.proxy(problem.newSign, problem));
$(".number").change($.proxy(problem.newNumber, problem));
})();
jsfiddle https://jsfiddle.net/czLtc82y/2/