By holyredbeard


2011-11-21 21:51:06 8 Comments

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!");
    }
};

2 comments

@Alex Wayne 2011-11-21 21:56:01

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();

@Matt Ball 2011-11-21 21:52:18

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

runApp.init();

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

Related Questions

Sponsored Content

32 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

36 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

34 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

69 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5130713 View
  • 6428 Score
  • 69 Answer
  • Tags:   javascript arrays

48 Answered Questions

[SOLVED] Loop inside React JSX

  • 2014-04-05 05:29:28
  • Ben Roberts
  • 558640 View
  • 796 Score
  • 48 Answer
  • Tags:   javascript reactjs

64 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

42 Answered Questions

[SOLVED] How do I check if an array includes an object in JavaScript?

21 Answered Questions

[SOLVED] Set a default parameter value for a JavaScript function

20 Answered Questions

[SOLVED] What is the difference between call and apply?

22 Answered Questions

[SOLVED] How can I add a key/value pair to a JavaScript object?

Sponsored Content