gpt4 book ai didi

javascript - 未捕获的 TypeError * 不是函数

转载 作者:行者123 更新时间:2023-11-27 23:29:31 25 4
gpt4 key购买 nike

我正在尝试使用 Object.prototype 进行编写和学习,但收到错误消息 this.issue当我在另一个方法中调用它时,它不是一个函数。我做错了什么导致它通过这个未捕获的类型错误?

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();

})();

});

更新:https://jsfiddle.net/czLtc82y/

最佳答案

在附加到 #signchange 事件的处理程序中,.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 对象
var problem = new Example();

尝试使用Function.prototype.bind()this 设置为 new Example() :.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/

关于javascript - 未捕获的 TypeError * 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34690107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com