簡體   English   中英

如何在自執行匿名函數內調用函數?

[英]how to call a function inside a self-executing anonymous 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) {

}

提供的代碼並不多,但是錯誤可能是由於您在匿名函數中引用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
})()

米奇發現的問題:既然你有一個回調函數的意義,這this變化。 你可以明確設置的值, this通過使用bind()

firebaseRef.on('value', function(dataSnapshot) {
    this.loadJson(JSON.stringify(dataSnapshot.val()));
}.bind(this));

請參閱: JavaScript'bind'方法的使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM