Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function different syntax? [duplicate]

Possible Duplicate: What is the difference between a function expression vs declaration in JavaScript? This JavaScript syntax I haven't seen till now, what does it do really?

What is the difference between the following two ways of writing a function? I've seen both used, but I'm not sure which one is 'correct'.

function init() {

}


init: function() {

},

And what are the advantages to writing it the second way?

like image 773
Dan Avatar asked Oct 09 '22 18:10

Dan


1 Answers

Function declaration

function init() {

}

Function expression

var init = function() {

};

The primary differences have to do with Variable Hoisting in JavaScript. You can read more here: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting and http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

By your example, I believe you are also interested in defining anonymous functions in object literals. Here is an example:

//obj is the object name
var obj = {
    //init is the property name or key and the anonymous function is the value
    init: function() {
    },
    anotherProp: 'some value'
};

This would be used like so:

obj.init();
alert(obj.anotherPorp);

In object literals different properties of the object are defined with a key: value syntax and use commas to separate them.

I would recommend going through this free series on JavaScript http://learn.appendto.com/lessons, it will answer a lot of these questions for you and give you a solid base to becoming a JS developer.

like image 126
Paul Avatar answered Oct 13 '22 11:10

Paul