2016-03-12 50 views
-1

我只是想調用自執行匿名函數內的函數。每當我試圖調用一個函數,我得到一個錯誤說「未捕獲的類型錯誤: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

請出示錯誤的完整軌跡。這個回調裏面應該指的是firebaseRef,它不會有loadJson方法。 –

+0

你正在代碼中調用一個未定義的函數'createGesture'。搜索你的文件並發表評論。 – Oden

+0

可能'this'不是你所期望的。閱讀[this](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – trincot

回答

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 
})() 
+0

非常感謝。有效。 :) –

+0

很高興我能幫到你 –

1

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

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

參見:Use of the JavaScript 'bind' method