Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Explanation of how you can call a function outside of an Object

We can be quite limited to storing functions inside an object, especially, if the function contains a lot of codes to run. The following code snippet shows the problem:

var myObj = {

sayHi: function(){

alert('Hi');

}

};

In the example above, all the function contents must be added inside the function code block, which can cause your object to store an unusually long code (considering that you have a lot of codes to run inside a function). A solution around this is to store a reference to the function you want to call inside an object key without the parentheses, so it will only be called once you want to call it. For example:

var myObj = {

myFunc: runFunc //Omit the parenthese after function name

};

function runFunc() {

    alert('Hello');

}

// Now the function is separate from the object and makes your codes more readable.

To call the function, access the object and the key that holds the function followed with parentheses, for example:

myObj.myFunc() //Add the parentheses to tell the interpreter to run the function