简体   繁体   中英

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"

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.loadJson(JSON.stringify(dataSnapshot.val()));

Try storing the this out of the anonymous function, and then using it in the anonymous function, like so

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. You can explicitly set the value of this by using bind() :

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

See: Use of the JavaScript 'bind' method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM