我只想在自动执行的匿名函数中调用一个函数。每当我尝试调用一个函数时,我都会收到一条错误说" Uncaught 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) {
}
答案 0 :(得分:2)
提供的代码并不多,但错误可能是由于您在匿名函数中引用this
这一事实。
this.loadJson(JSON.stringify(dataSnapshot.val()));
尝试将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()));
});
}
作为注释,您提供的代码中没有自调用函数。自调用函数看起来像这样
(function() {
//code
})()
答案 1 :(得分:1)
Mitch确定了问题:由于你有一个回调函数,this
的含义会发生变化。您可以使用this
:
bind()
的值
firebaseRef.on('value', function(dataSnapshot) {
this.loadJson(JSON.stringify(dataSnapshot.val()));
}.bind(this));