【问题标题】:how to call a function inside a self-executing anonymous function?如何在自执行匿名函数中调用函数?
【发布时间】:2016-03-12 21:41:10
【问题描述】:

我只是想在一个自动执行的匿名函数中调用一个函数。每当我尝试调用一个函数时,我都会收到一条错误消息“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 应该是指没有加载 loadJson 方法的 firebaseRef。
  • 您在代码中的某处调用了一个未定义的函数createGesture。搜索您的文件并发表评论。
  • this 可能不是您所期望的那样。阅读this

标签: javascript firebase


【解决方案1】:

提供的代码不多,但错误可能是由于您在匿名函数中引用了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
})()

【讨论】:

    【解决方案2】:

    Mitch 发现了问题:由于您有一个回调函数,this 的含义发生了变化。您可以使用bind() 显式设置this 的值:

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

    见:Use of the JavaScript 'bind' method

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      相关资源
      最近更新 更多