2

I am kind of oldskool and just getting back to learning about all the new stuff added to JS in the last 10 years or so (or just stuff I did now know about back then) and would like to know whats the difference between

function xyz() // I used to always use it like this
{}

and this that I keep seeing:

xyz:function()
{}

It also has a funny little comma with two or more functions like so:

xyz1:function()
{},
xyz2:function()
{}
1

3 Answers 3

5

That's when you are creating an object with function inside it:

var functions = {

    xyz1:function(){},
    xyz2:function(){}

}

Now I can do:

functions.xyz1();
//or:
functions.xyz2();
Sign up to request clarification or add additional context in comments.

Comments

3
xyz:function()
{}

alone is invaid syntax. The key: value notation, however, is used in objects.

For example,

var functions = {
    xyz: function()
         {}
}

Then you can call it like functions.xyz().

This is very popular these days with libraries like jQuery, where you are often working with objects which contain a set of functions.

Comments

1

Both are perfectly valid ways of defining a function.

The second function is an example of Javascript object notation, and it can be leveraged to make a more easy to understand Object orientated javascript 'class'.

See my answer to this question to see an example of this:

function in JSON format - possible?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.