[英]how to call a function inside a self-executing anonymous function?
I just to wanted to call a function inside a self-executing anonymous function. 我只是想在自执行匿名函数中调用一个函数。 Whenever I try to call a function, I am getting an error saying "Uncaught TypeError: createGesture() is not a function" 每当我尝试调用一个函数时,我都会收到一条错误消息:“未捕获的TypeError:createGesture()不是函数”
loadGesturesFromDatabase: function() {
var firebaseRef = new Firebase("https://test.firebaseio.com/");
this.loadFromFireBase(firebaseRef);
firebaseRef.on('value', function(dataSnapshot) {
dataSnapshot.val();
console.log(dataSnapshot.val()); // console showing the data //which fetched from firebase
//Only having issue when executing following line of code
this.loadJson(JSON.stringify(dataSnapshot.val()));
});
}
loadJson: function(json) {
}
The provided code is not much to go by, but the error is probably caused by the fact that you refer to this
inside an anonymous function. 提供的代码并不多,但是错误可能是由于您在匿名函数中引用this
代码引起的。
this.loadJson(JSON.stringify(dataSnapshot.val()));
Try storing the this
out of the anonymous function, and then using it in the anonymous function, like so 尝试存储this
了匿名函数,然后在匿名函数使用它,像这样
loadGesturesFromDatabase: function () {
var firebaseRef = new Firebase("https://test.firebaseio.com/");
//We keep a reference to the correct this
var _this = this;
this.loadFromFireBase(firebaseRef);
firebaseRef.on('value', function(dataSnapshot) {
dataSnapshot.val();
console.log(dataSnapshot.val()); // console showing the data //which fetched from firebase
//You are now referencing the correct this
_this.loadJson(JSON.stringify(dataSnapshot.val()));
});
}
As a note, there are no self invoking functions in the code you provided. 请注意,您提供的代码中没有自动调用功能。 A self invoking function looks like this 自我调用功能如下所示
(function() {
//code
})()
Mitch identified the problem: since you have a callback function, the meaning of this
changes. 米奇发现的问题:既然你有一个回调函数的意义,这this
变化。 You can explicitly set the value of this
by using bind()
: 你可以明确设置的值, this
通过使用bind()
firebaseRef.on('value', function(dataSnapshot) {
this.loadJson(JSON.stringify(dataSnapshot.val()));
}.bind(this));
See: Use of the JavaScript 'bind' method 请参阅: JavaScript'bind'方法的使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.