Functions Declarations [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?
What is the right way to declare Javascript Function?
From codeacademy.com i got this way:
var someFunction = function(paramA, paramB){
// do some function here
}
But because my basic of programming is PHP, i prefer declare function with this way:
function someFunction(paramA, paramB){
// do some function
}
What I'm concern is which one is recommended way to declare function, I'm afraid if my preferred way have some consequences, but i love that way so much because it make my NetBeans Code Navigator can read all of my functions.

Both are acceptable. Indeed, you can also do:
foo = function bar() {
console.log(arguments.callee.name);
};
If you then call foo(), you'll see "bar" in the console.
The first method creates an anonymous function and assigns it to a variable.
The second method creates a named function and places it within the current scope.
The third method creates a named function and assigns it to a variable. However, this time, the name only exists within the scope of that function.
Declaring a function with a name (function name () {}) has the advantage that you can then call the function more easily from inside itself, as may be necessary for implementing a recursive algorithm. If you don't, you have to use arguments.callee.name in order to call a function within itself, but that is warned against in MDN.
All of that is a long-winded way of saying that either is acceptable and, if in doubt, you can't go much wrong with using named functions.

Related

declaring javascript private methods [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
In Javascript, "private methods" are basically just inner functions. But throughout the various javascript tutorials available online, there seems to be two practices for declaring private methods:
function foo()
{
var privateMethod = function() { }
}
versus...
function foo()
{
function privateMethod() { }
}
They both seem to achieve the same effect, i.e. privateMethod is not accessible publicly through an instance of foo. The only difference seems to be with the first way (using the var keyword), privateMethod is only available to code that comes after the declaration. But with the second way, privateMethod is available to all code within foo. So, is there any other difference that makes either of these two practices preferable?
There's another major difference: In the first example, the function is anonymous. The variable it's assigned to has a name, but the function itself does not. This matters when you're using the debugger and looking at lists of breakpoints, the call stack, etc.
Another major difference is that the first, which is called a function expression, happens as of when the execution point reaches that part of the code, which means you can assign different functions to the variable depending on the logic flow if you want. The second, which is called a function declaration, is only valid at the top level of its containing scope (not within an if block, a try/catch, etc.), and happens when execute enters that containing scope (before any step-by-step code is run).
You might well be tempted to combine the two, using a named function expression:
var foo = function foo() { ... };
...but sadly although it should be valid, various JavaScript engines (primarily Microsoft's) handle those incorrectly.

what's the difference between var function and function in javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
Function declaration - Function Expression - Scope
I've learned about var a = 1, is defining a local variable, but talk about function, I thought It's only available within the current scope as the var variable behave, what's the difference between the following two code snippet?
function aPrint() {
console.log('a');
}
var a = function aPrent() {
console.log('a');
}
Your first example is a "function declaration". It declares a function that will be available anywhere in the scope in which it is declared (so you can call it before it appears in the source code). This is sometimes known as "hoisting" (as in, it gets hoisted to the top of its scope).
Your second example is a "named function expression". The variable declaration is hoisted to the top of the scope in which it is defined (like a function declaration) but the assignment still happens where you expect it to, so you can't call the function until after it has been assigned to the variable.
There is a third option, which is just a "function expression", where the function does not have a name (it's an anonymous function):
var a = function() {
console.log('a');
}
You will probably find that you have little use for named function expressions (although it can be useful when debugging), so it's usually better to use the anonymous function. In a named function expression, the name is only in scope inside the function itself, so you can't refer to the function by name normally.
here is a best article that may help you.
refer http://www.dustindiaz.com/javascript-function-declaration-ambiguity/
function aPrint() {}
Declares a function (but does not execute it).
It will usually have some code between the curly brackets.
var a = aPrint()
Declares a variable, invokes a function (aPrint) and sets the value of aPrint to the return of the function.
var a= new aPrint()
Creates a new instance of an object based on the aPrint function. So the variable is now an Object, not just a string or a number.
Objects can contain indexed strings, numbers and even functions, and you can add more stuff to them, they're pretty awesome. The whole concept of Object Oriented Programming (OOP) is based on this.

JavaScript notation: (function() { ... } )(); [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
Hello all,
I have seen several JavaScript files using this notation:
Start of JavaScript file:
(function() {
// All functions go here.
// Can someone say what the wrapping nameless function is used for?
})();
Also with the prototype library, this seems possible:
function $() {
// Prototype $-wrapping function.
}
Can someone please explain the above two code fragments, their uses and their differences? Some keywords which would help me find more about this notation/technique (how it is named) would be helpful too so I can run a Google search on it... :)
Thanks!
In your first example, people surround their code in an anonymous function for scoping reasons, to avoid global namespace cluttering. That weird parentheses syntax is used to define and execute the function all in one step; the () at the end has the meaning of executing the function itself.
So inside that anonymous function you could define function apple(){} and it would only be accessible inside that anonymous function. This is good if you're making a library and want only certain things to clutter your global namespace.
Your second example is just a simple function called $. Many libraries like to use this name because it's short and concise, and since you need to type it every time you want to reference the libraries namespace, the shorter, the better.
I searched for "javascript wrapping function" and the first hit was this, which says:
This method doesn't add any new symbols to the global or LIB spaces.
I don't understand the second part of the question: function $() { ... } isn't a "nameless" function: it has the name $! If you like functions named $ it's the most straightforward way I know of to make such a thing.
An annonymous function is defined
function() {
}
and then immediately called
()
The extra () enclosing the function is to force the interpreter to treat the function as an expression. Javascript treats any statement starting with the function keyword as a declaration so it could not otherwise be immediatly called.
The purpose is to avoid polluting the global namespace. All variables defined in the function will be local to the function.
Google for module pattern.
retracted in favor of answer to: What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
First one is called immediate function. You can read more about this function pattern here.

What's the difference between this two ways of defining a function in JavaScript? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}
Way 1:
function fancy_function(){
// Fancy stuff happening here
}
Way 2:
var fancy_function = function(){
// Fancy stuff happening here, too.
}
I use the former when I'm just defining a "normal" function that I'm gonna use one or several times and the latter when I'm passing it a callback for another function or so, but it looks to work fine in the both ways.
Is it really a difference in some way?
There is no difference to the function itself, but the latter gives you more flexibility as you have a reference to the function and it is different with regard to how it behaves if overwritten.
This allows you to achieve behaviours with the latter that you cannot achieve with the former; such as the following trick to "override" an existing function and then call the "base":
var myOriginalFunction = function() {
window.alert("original");
}
var original = myOriginalFunction;
var myOriginalFunction = function() {
window.alert("overridden");
original();
}
myOriginalFunction();
This gives you an alert "overridden", followed by an alert "original".
However, if you attempt this with the former notation, you'll find you get stuck in a never ending loop of alert "overidden".
In the first sample you are defining a named function -- that function will always be known by that name. Defining a different function with the same name will be an error (unless you assign to the window property directly). In the second sample, you are defining an anonymous function and assigning it as the value of a variable. You can change the value of the variable to any other function later as desired; losing, of course, any reference to the anonymous function in the process unless you've stored it elsewhere. So, you're not really doing the same thing in both cases, though you can treat it that way if you wish -- and make sure to define the function before it's used in the second case, though that's more a function of variables than functions per se.
function definition
function literal assignment
only difference is you can access the former instantly in certain cases whereas you have to wait for the assignment on the latter.
Don't run this in firebug console/interpreter to test it, rather test on a real html page.
say('spotted');
function say(msg){ alert(msg) }
The above will work, but if you defined a function literal with var say = function(){} below, it would complain that it isn't defined yet.
You can use either depending on the situation, both become the methods of the window object. The later is known as anonymous function.
As far as the function is concerned, they will behave identically.
See here for more details: http://javascript.about.com/library/blfunc.htm
Functions defined with the Function(){} style are available throughout the program, without having to be defined earlier in the code than where they are called. It's called 'hoisting', I believe.
so this works
cow('spotted');
function cow(color){ return 'cow is '+color; }
but this throws an error
cow('spotted');//cow isn't defined yet!
var cow=function(color){ return 'cow is '+color; }

Javascript: Calling a function written in an anonymous function from String with the function's names withoout eval?

Update2:
What I really wanted to ask was already argued in a different page. Please check the following entry. (Thanks to BobS.)
How can I access local scope dynamically in javascript?
Hello.
I've started using jQuery and am wondering how to call functions in an anonymous function dynamically from String.
Let's say for instance, I have the following functions:
function foo() {
// Being in the global namespace,
// this function can be called with window['foo']()
alert("foo");
}
jQuery(document).ready(function(){
function bar() {
// How can this function be called
// by using a String of the function's name 'bar'??
alert("bar");
}
// I want to call the function bar here from String with the name 'bar'
}
I've been trying to figure out what could be the counterpart of 'window', which can call functions from the global namespace such as window["foo"].
In the small example above, how can I call the function bar from a String "bar"?
Thank you for your help.
Update:
Here's what I want:
Define functions that are only used in the closure.
Avoid creating an Object in the closure that holds those functions in order to be accessed as obj['bar'].
Avoid eval (if possible) in order to write code more simply in a straightforward manner (if exists).
Decide function's name dynamically via the URI parameter or anything variable.
Being a newbie of Javascript, I thought 'this' would be the counterpart of 'window' in the closure, and tried writing:
// in the closure
name = 'bar';
this[name]; // undefined ...
and failed (of course...).
All of these are for pursuit of further laziness. Javascript is kind of new to me and currently I've been trying to write code as lazy as possible.
As Kobi wrote, eval might be a good option. Alternatively, is there any reason not to do
$(function(){
var localNamespace = {};
function bar() {
alert("bar");
}
localNamespace['bar'] = bar;
// Now bar() can be called by, well, localNamespace['bar']
}
Update:
Similar SO entries, such as How can I access local scope dynamically in javascript?, seem to indicate you're out of luck without using one of these two approaches or something even uglier.
Inside your ready function:
window.bar = function bar() {
// ...
}
Then, you can access window['bar'].

Categories