1

我正在尝试将字段的值设置为函数,然后执行它。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没有运气。我错过了什么吗?

4

2 回答 2

1

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

在创建对象之前,您不能引用对象的其他属性。因此,只需在创建对象后正常调用该函数即可。

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

};

app.busdata = app.fetchLocalStorage();

于 2018-04-11T22:52:57.997 回答
0

我认为您的参数在支架的错误一侧。

busdata: (function(){return this.fetchLocalStorage()}() ),
于 2018-04-11T22:52:42.063 回答