开发者

Javascript Syntax Differences

What is the difference between these two?

collapse: function(fold)
{
开发者_JAVA技巧...
...
}

and

function collapse(fold)
{
...
...
}


The first one outside of the context of an object literal is a syntax error.

However, I believe you are asking about the difference between a function expression and a function declaration.

Your first one is a function expression. You assign an anonymous function to a variable. Its variable definition is hoisted to the top of its scope, but not the assignment of the function.

The second is the function declaration. Its entire body is hoisted to the top of the scope.

In general, a function expression is often used as it is more expressive. You can give it a name if you need to call it recursively (or for better detailed stack traces), but remember IE leaks this name to the outer scope.

Further Reading.


The first code is only valid to produce a property inside an object definition, like so:

var obj = {
    collapse: function(fold)
    {
    ...
    ...
    }
};

That function would be called by calling obj.collapse(fold);

The second function is simply called using collapse(fold);

As for the difference between var name = function() { ... } and function name() { ... } see: var functionName = function() {} vs function functionName() {}


The first syntax declares a method on an object. The second declares a regular function.


The first one is not valid JavaScript, I'll assume that you meant =, not :. This is the same in global scope, first one uses an anonymous function and the second is just some syntactic sugar to name a function. The difference would be that in non global scope first one would produce a function in global scope, the second would be created in most recent scope (for the same effect use var x = function() {} in the first example).


The first one is creating a property called "collapse" on whatever the current object is (or if there is no current object, then it will error out) and assigning a function to it. The function will only be accessible through its associated object, by calling something along the lines of obj.collapse();.

The second one is creating a function called "collapse" in the global namespace (i.e. as a property on window). The function can be called from anywhere by doing collapse();.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜