gpt4 book ai didi

JavaScript: 调用函数时出现 TypeError: xyz 不是函数

转载 作者:行者123 更新时间:2023-12-03 07:49:38 24 4
gpt4 key购买 nike

我试图创建一个页面,当用户单击页面上的文件按钮时,我尝试在页面上执行 JS。我正在尝试使用 OOP/类,因此希望它可以在以后重用。这是我的测试代码:

// This is the "class". 
function BearUpload() {
// some values will go here...
}

// Add a few functions
BearUpload.prototype.function1 = function () {
console.log("function1 called");
}

BearUpload.prototype.handleFileSelect = function (evt) {
console.log("handleFileSelect called");

this.function1();
}


var myBear = new BearUpload(); // Create a global variable for the test


$(document).ready(function () {
var some_condition_goes_here = true;
if (some_condition_goes_here) {
$("#my-file-select-button").change(myBear.handleFileSelect);
}
});

但是,它会出现如下错误:

TypeError: this.function1 is not a function

this.function1();

对此有什么想法吗?

谢谢!

最佳答案

绑定(bind)myBear给您change事件监听器

一般来说,当您访问this时来自handleFileSelect , this指的是 html 元素。
this =<input type="file" id="my-file-select-button">

$("#my-file-select-button").change(myBear.handleFileSelect.bind(myBear));

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

MDN doc

关于JavaScript: 调用函数时出现 TypeError: xyz 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35055001/

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