JavaScript:TypeError:xyz 在调用函数时不是函数
JavaScript: TypeError: xyz is not a function when calling the function
我正在尝试提出一个页面,当用户单击页面上的文件按钮时,我尝试在页面上执行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;
...
}
}
相关文章:
- TypeError:_this.store.getState在使用来自Redux的连接时不是函数
- Uncaught TypeError:undefined不是函数-ember js
- 试图将onChange函数作为道具传递给GrandChlidren,结果是TypeError:这是未定义的
- Mongoose TypeError:实例化模式类型的对象时,对象不是函数
- jQuery使用ajax自动完成问题-TypeError:this.source不是函数
- TypeError:this.getAttribute不是一个函数-javascript
- poster typeerror用户不是函数
- TypeError:t(..).on不是fullcalendar上的函数
- jQuery$.post TypeError:e.type不是函数
- TypeError:执行回调时,回调不是函数
- Dojo:TypeError:marketStore.query不是函数
- 未能运行构造函数:TypeError:对象#<对象>没有方法'addPlugin'
- 尝试使用.ninnerHTMLlog打印数据,获取错误Uncaught TypeError:undefined不是函数
- 我收到此错误Uncatch TypeError:this.getElements不是一个函数
- Getting TypeError:$(..).datetimepicker不是函数
- TypeError:socket.emit不是函数
- node.js中的回调函数.TypeError: Cannot call method 'emit'的定
- 调用javascript函数TypeError时出错:i.contentWindow.hiform不是函数
- Javascript 函数 TypeError 但只在 substring() 字符串上
- JS:你的函数不是一个函数!TypeError