JavaScript:TypeError:xyz 在调用函数时不是函数

JavaScript: TypeError: xyz is not a function when calling the function

本文关键字:函数 TypeError xyz JavaScript 调用      更新时间:2023-09-26

我正在尝试提出一个页面,当用户单击页面上的文件按钮时,我尝试在页面上执行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();

对此有任何想法吗?

谢谢!

myBear绑定到change事件侦听器

通常,当您从 handleFileSelect 访问this时,this指的是 html 元素。
this = <input type="file" id="my-file-select-button">

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

bind() 方法创建一个新函数,该函数在调用时具有其 此关键字设置为提供的值,具有给定的序列 调用新函数时提供的任何参数前面的参数。

MDN 文档

您正在尝试在 DOM 对象上调用 function1,但您必须调用 jQuery 对象

$(this).function1();

这是因为当作为处理程序绑定到 jQuery 事件时,这将引用触发事件的元素。

我宁愿像这样更改您的代码

// Create only one global variable for your app
var APP = {};
// Create class using immediate function/closure
APP.BearUpload = (function(){
//declare private variables here
// Constructor
var bearUpload = function() {
    // 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();
}
return bearUpload;
}());

APP.myBear = new APP.BearUpload(); 

$(document).ready(function () {
    var some_condition_goes_here = true;
    if (some_condition_goes_here) {
        $("#my-file-select-button").change(function(e){
           // do something with event 'e'
           APP.myBear.handleFileSelect.call(APP.myBear, e);
        });
    }
});
不要

使用"this",这有时会令人困惑。

BearUpload.prototype ={
     function1:function(){
         var self = this;
         ...
     },
     handleFileSelect:function(e){
        var self = this;
        ...
     }
}