Javascript function declaration. When to use what? [duplicate]
开发者_StackOverflowPossible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}
What is the reason you would do:
somename = function(param1, param2) { }
In stead of doing:
function somename(param1, param2) { }
Well since the 1st syntax is a variable declaration and the 2nd is an actual function declaration, i would stick to the 2nd unless I truly needed the 1st.
Try to read up on scoping and variable hoisting and you will see that the 2nd syntax can sometimes create trouble for you :)
http://www.dustindiaz.com/javascript-function-declaration-ambiguity/
http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
Btw, you might want to browser this thread and look for more good stuff: var functionName = function() {} vs function functionName() {}
$fn = function(param1, param2)
By using the above form you are able to pass $fn to any function as a parameter, or you could create a new object from that:
function doSomethingWithFn($fn);
or
$fnObject = new $fn(param1, param2)
You can use the second form when you just need a utility function, or for closures:
function utilityFn(str) {
return str.indexOf('a')
}
var str = utilityFn('abc');
or
$('#element').click(function() {
utiliyFn($('#element').html())
})
The first method creates a function object that you can then pass as parameter to other functions. For example, if you want to execute some code when a text box value changes, you can set a callback like this (using jQuery):
var onChange = function() { /* ... */ }
$("#username").change(onChange);
精彩评论