Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: creating a function

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()
{}
like image 713
Ryan Avatar asked Jan 17 '26 22:01

Ryan


2 Answers

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();
like image 128
Naftali Avatar answered Jan 19 '26 16:01

Naftali


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.

like image 20
pimvdb Avatar answered Jan 19 '26 15:01

pimvdb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!