开发者

scripting subtlties [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

When to use anonymous JavaScript functions?

Is there any difference between var name = function() {} & function name() {} in Javascript?

in javascript (and other scripting language开发者_运维知识库s) what is the 'real' difference between these two syntax:

a) function myFun(x) { yadda yadda }

b) myFun(x) = function { yadda yadda }

to a casual observer - no 'real' difference - you still call either as myFun()...and they still return the same thing, so if reference and return are identical - is it a preference or is there some difference in the code parsing engine that treats these two differently - and if so - when would you use one over the other???


The real, super-secret difference:

foo(); // succeeds
function foo() { alert("hi"); }

bar(); // fails
var bar = function() { alert("hi"); }

The former syntax hoists the function such that (although arguably bad practice) it can be called before its actual line in the code. The latter syntax requires you to declare the function first.


You actually mean var myFun = function(x) { ... }.

If you don't put the var there (bad), it becomes a global variable, which is not what you want. The function syntax will automatically restrict the variable to be a local I think, but people use both syntaxes.

Otherwise the difference is so minor that it is not worth caring about, but you can see the accepted answer on When to use anonymous JavaScript functions?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜