如何在自执行匿名函数内调用函数?

时间:2016-03-12 21:41:11

标签: javascript firebase

我只想在自动执行的匿名函数中调用一个函数。每当我尝试调用一个函数时,我都会收到一条错误说" 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) {

}

2 个答案:

答案 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));

请参阅:Use of the JavaScript 'bind' method