我试图创建一个页面,当用户单击页面上的文件按钮时,我尝试在页面上执行 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.
关于JavaScript: 调用函数时出现 TypeError: xyz 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35055001/