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

时间:2016-01-28 07:13:44

标签: 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();

对此有何想法?

谢谢!

4 个答案:

答案 0 :(得分:1)

myBear绑定到您的change eventListener

通常,当您从this访问handleFileSelect时,this会引用html元素。
 即this = <input type="file" id="my-file-select-button">

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

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

MDN doc

答案 1 :(得分:0)

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

$(this).function1();

答案 2 :(得分:0)

那是因为当绑定为jQuery事件的处理程序时, this 会引用触发事件的元素。

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

// 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);
        });
    }
});

答案 3 :(得分:0)

不要使用“这个”,这有点困惑。

BearUpload.prototype ={
     function1:function(){
         var self = this;
         ...

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

     }

}