javascriptfunctionobjectthisself-executing-function

Exception when calling a self-executing function in an object literal


I'm trying to set a field's value to a function, then execute it. this.fetchLocalStorage is not a function is what I get from running it.

var app = {

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

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

};
console.log(app.busdata);

Note that by not making it a self-executing function, it works, but then it would mean the function is called everytime when I only need to fetch the data one time.

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

Thought it might a context problem so I tried a couple things with bind and call but with no luck. Am I missing something?


Solution

  • this is only bound to the object when you call a method of the object, i.e. app.someMethod(). But you're trying to call fetchLocalStorage() when you're creating the object, not in a method of the object, so this is whatever the outer context is, which is likely the global window object.

    You can't refer to other properties of the object until after the object has been created. So just call the function normally after you create the object.

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