Is the JavaScript function different in syntax?

Possible duplicate: What is the difference between a function expression and a declaration in JavaScript? This JavaScript syntax that I still haven't seen, what does it really do?

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

function init() {

}


init: function() {

},

And what are the benefits of writing a second way?

+5
source share
4 answers

Function Declaration

function init() {

}

Functional expression

var init = function() {

};

Variable Hoisting JavaScript. : http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

, , anonymous functions object literals. :

//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'
};

:

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

key: value .

JavaScript http://learn.appendto.com/lessons, , JS.

+4

:

init: function (){

}

.

, var , :

var init = function(){

}

, , , , .

, . sloppier , , ... , .

function init(){

}
0

:

var myNamespace = {
    func1: function () {
        // do something
    },

    func2: function () {
        // do something else
    },

    someValue = 5
};

. :

var init = function () {
    // do something
};
0

The first example defines a function in a global scope that can be called with init(). The second defines a property of an object with a name init, which is a function declaration on the right.

Typically, the second example provides a smaller area in which you could perform this function.

The first example allows you to call this function:

init();

And second, more likely the following:

var thing = function() {
    init: function() { }
};

thing.init();
0
source

All Articles