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

79 Answered Questions

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

  • 2011-04-23 22:17:18
  • Walker
  • 5781382 View
  • 7209 Score
  • 79 Answer
  • Tags:   javascript arrays

69 Answered Questions

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

35 Answered Questions

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

38 Answered Questions

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

23 Answered Questions

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

38 Answered Questions

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

52 Answered Questions

[SOLVED] Loop inside React JSX

  • 2014-04-05 05:29:28
  • Ben Roberts
  • 675988 View
  • 1005 Score
  • 52 Answer
  • Tags:   javascript reactjs

10 Answered Questions

20 Answered Questions

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

23 Answered Questions

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

Sponsored Content