如何在自执行匿名函数内调用函数? [英] how to call a function inside a self-executing anonymous function?

查看:63
本文介绍了如何在自执行匿名函数内调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想在自执行匿名函数中调用一个函数.每当我尝试调用函数时,我都会收到一条错误消息,提示未捕获的TypeError:createGesture()不是函数"

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) {

}

推荐答案

所提供的代码并不多,但是错误可能是由于您在一个内部引用 this 匿名功能.

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()));

尝试将 this 存储在匿名函数之外,然后在匿名函数中使用它,就像这样

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

这篇关于如何在自执行匿名函数内调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆