I would like to know what is hide under some specifics ways to execute some code.
I have 3 different ways to do in my mind, but i really don’t know which is better on what kind of situation and why.
I just choose the Case 2 method most of the time for a syntaxical preference, but i am more and more wondering what are the advantages and disadvantages of each method.
Case 1:
var response = Func();
//Handle response...
Case 2:
Func(response){
//Handle response...
};
Case 3:
Func({
case_x: function(opt){
//Handle an example case...
}
});
Thanks for the explanations i am very curious about that !
Assuming that Func is an existing function:
Case 1 is if your function returns a value and you want to store the result, such as in:
So now you can use the variable
hundredfrom now on.Case 2 is if you are not returning a value, or you don’t need to save it:
Case 3 is slightly more complex.
If you do
var something={a:function(){}}– By creating an object like this, you have all of your functions in the same scope, so you don’t pollute the global namespace. This is kind of like creating a class in other languages. jQuery is the biggest example of this I can think of, because for all of what it does, it all is processed by the objectjQuery(or calling a function such asjQuery.parseJSON(json_string)If you’re passing in an object with a function like that, then you are asking
Func()to do something with that function you passed in, like so:Which would now write out 1000, not 100.