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

标签 javascript jquery

我试图创建一个页面,当用户单击页面上的文件按钮时,我尝试在页面上执行 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/

相关文章:

Javascript - 通用 Windows 应用程序 - 捕获关闭事件

javascript - 如何使可拖动元素跟随鼠标指针

javascript - jQuery 验证 : how to make the amount of characters no include the tokens generated by CKEditor?

jquery - 将 CSS3 转换和动画与 jQuery addClass/removeClass 结合使用的最佳方法是什么?

jquery - jQuery 中获取 prop ('tagName' ) 问题

JavaScript 类与 TypeScript 类

有关动态创建的 HTML 事件的 JavaScript 问题

javascript - 如何通过解析 JSON 文件来分配 JavaScript 变量?

javascript - 循环遍历 Google map 的 JSON 数据

javascript - 如何使用 Codeigniter 从 Ajax Jquery 中的 Controller 获取多个参数?