45

I'm learning to use object literals in JS, and I'm trying to get a function inside an object to run by calling it through another function in the same object. Why isn't the function "run" running when calling it from the function "init"?

var RunApp = {

    init: function(){   
         this.run()
    },
    
    run: function() { 
             alert("It's running!");
    }
};
Irshu
  • 8,248
  • 8
  • 53
  • 65
holyredbeard
  • 19,619
  • 32
  • 105
  • 171

3 Answers3

56

That code is only a declaration. You need to actually call the function:

RunApp.init();

Demo: http://jsfiddle.net/mattball/s6MJ5/

Irshu
  • 8,248
  • 8
  • 53
  • 65
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
13

There is nothing magical about the init property of an object, which you happen to have assigned a function to. So if you don't call it, then it won't run. No functions are ever executed for you when constructing an object literal like this.

As such, your code becomes this:

var RunApp = {
    init: function(){   
         this.run()
    },
    run: function() { 
         alert("It's running!");
    }
};

// Now we call init
RunApp.init();
Irshu
  • 8,248
  • 8
  • 53
  • 65
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
2

You can try the following code. It should work:

var RunApp = {

  init: function(){   
     RunApp.run()
  },

  run: function() { 
     alert("It's running!");
  }
};
Irshu
  • 8,248
  • 8
  • 53
  • 65
simba
  • 59
  • 3