【问题标题】:Exception when calling a self-executing function in an object literal在对象字面量中调用自执行函数时出现异常
【发布时间】:2018-09-21 22:46:59
【问题描述】:

我正在尝试将字段的值设置为函数,然后执行它。 this.fetchLocalStorage is not a function 是我运行它的结果。

var app = {

  busdata: (function(){return this.fetchLocalStorage()})(),

  fetchLocalStorage: function() {
    //fetching
    return "fetching data...";
  }

};
console.log(app.busdata);

请注意,通过不使其成为自执行函数,它可以工作,但这意味着每次我只需要获取一次数据时都会调用该函数。

busdata: function(){return this.fetchLocalStorage()}
/* ... */
console.log(app.busdata()); //this calls the function every time :(

认为这可能是上下文问题,所以我用bindcall 尝试了几件事,但没有运气。 我错过了什么吗?

【问题讨论】:

    标签: javascript function object this self-executing-function


    【解决方案1】:

    this 仅在调用对象的方法时绑定到对象,即app.someMethod()。但是您在创建对象时尝试调用fetchLocalStorage(),而不是在对象的方法中,因此this 是外部上下文,可能是全局window 对象。

    在创建对象之前,您不能引用对象的其他属性。所以在创建对象后正常调用函数即可。

    var app = {
      fetchLocalStorage: function() {
        //fetching
        return "fetching data...";
      }
    
    };
    
    app.busdata = app.fetchLocalStorage();

    【讨论】:

      【解决方案2】:

      我认为您的参数在大括号的错误一侧。

      busdata: (function(){return this.fetchLocalStorage()}() ),
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-02
        • 1970-01-01
        • 1970-01-01
        • 2015-10-06
        • 2020-02-08
        • 2016-03-31
        • 2013-02-12
        相关资源
        最近更新 更多