declaring javascript private methods [duplicate] - javascript

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.

Related

What's the difference between a javascript function as a property of window, a function defined with a name [duplicate]

This question already has answers here:
What is the difference between these two functions/approaches?
(4 answers)
Closed 9 years ago.
What's the difference between
function doStuff(){
//do lots of fun stuff
}
and
window.doStuff = function(){
//do lots of fun stuff
}
if any?
The first will create a doStuff function property in whatever is the current scope context. If that is window (or no scope defined), then the result will be the same as the second in a browser context. If the current scope, though, is for example within another function, then only a locally available function will be created and the effect will not be the same as the bottom.
There is no big difference if you declare function in global scope.
Difference appears when scope of code, where you are declaring a function is not global.
For example, inside another function:
function doGlobalStuff()
{
function doStuff(){
// do lots of fun stuff
}
}
If you execute doGlobalStuff() function window object will contain doGlobalStuff() method, but there is no doStuff() method in there.
However, this function will create method doStuff() in window object:
function doGlobalStuff()
{
window.doStuff = function(){
// do lots of fun stuff
}
}
Search for variable and function scope for more info, like this:
What is the scope of variables in JavaScript?
There is no difference between these two as long as the first is declared in a global scope.
The first will work out of browser contexts, where window isn't available. It also has a name (regardless of what variable or method key it's assigned to), which is useful for, among other things, stack traces and recursion.
The second won't work in, say, node.js (although global would). It doesn't have a name of it's own, which makes recursion difficult, as in the following example:
window.doStuff = function( i ){
if( --i ){
return window.doStuff();
}
return i;
}
If window.doStuff gets assigned something else, as follows…
window.doStuff = 'erg';
…then the above function breaks, because it's anonymous and can't reference itself — it's essentially lost.
Of course, there's nothing stopping you from doing both:
window.doStuff = function doStuff(){
//do lots of fun stuff
}

Functions Declarations [duplicate]

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.

Function decaration in Javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between a function expression vs declaration in Javascript?
Is there a MAJOR difference between declaring functions in these ways:
function foo(){
alert('BAR');
}
var foo = function (){
alert('BAR');
}
var foo = function bar(){
alert('BAR');
}
I was told here that:
It happens at a different time, and results in a variable referring to an anonymous function. A function declaration happens prior to any stepwise code executing in the scope, and results in both a binding and a function with a proper name.
Can the way I declare my function really affect the efficiency of my code, and if so which way is best to use?
Yes, there is a major difference.
The first is a function declaration. It happens upon entry to an execution context, prior to any step-by-step code being processed. It cannot be within any kind of control block (e.g., it's not legal in the body of an if statement; however, most browsers will try to accommodate it if you do that — sometimes resulting in very surprising behavior — at variance with the spec). It results in a named function.
The second is a function expression (specifically, an anonymous function expression). Like all expressions, it's processed when it's encountered in the step-by-step execution of the code. And like all expressions, it can be within a control block. It results in a function with no name assigned to a variable that has a name.
The third is a named function expression. It's a function expression like the above, but the function is also given a name. You want to avoid these with IE8 and earlier, since IE will actually get it quite wrong, creating two separate functions (at two different times). (Basically, IE treats it as both a function declaration and a function expression.) IE9 finally gets this right.
Note that your second and third examples rely on automatic semicolon insertion; because those are both assignment statements, they should end with a ; (after the ending } of the function).

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.

whats the difference between function foo(){} and foo = function(){}? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
are they the same? I've always wondered
No, they're not the same, although they do both result in a function you can call via the symbol foo. One is a function declaration, the other is a function expression. They are evaluated at different times, have different effects on the scope in which they're defined, and are legal in different places.
Quoting my answer to this other question here (edited a bit for relevance), in case the other question were ever removed for some reason (and to save people following the link):
JavaScript has two different but related things: Function declarations, and function expressions. There are marked differences between them:
This is a function declaration:
function foo() {
// ...
}
Function declarations are evaluated upon entry into the enclosing scope, before any step-by-step code is executed. The function's name (foo) is added to the enclosing scope (technically, the variable object for the execution context the function is defined in).
This is a function expression (specifically, an anonymous one, like your quoted code):
var foo = function() {
// ...
};
Function expressions are evaluated as part of the step-by-step code, at the point where they appear (just like any other expression). That one creates a function with no name, which it assigns to the foo variable.
Function expressions can also be named rather than anonymous. A named one looks like this:
var x = function foo() { // Valid, but don't do it; see details below
// ...
};
A named function expression should be valid, according to the spec. It should create a function with the name foo, but not put foo in the enclosing scope, and then assign that function to the x variable (all of this happening when the expression is encountered in the step-by-step code). When I say it shouldn't put foo in the enclosing scope, I mean exactly that:
var x = function foo() {
alert(typeof foo); // alerts "function" (in compliant implementations)
};
alert(typeof foo); // alerts "undefined" (in compliant implementations)
Note how that's different from the way function declarations work (where the function's name is added to the enclosing scope).
Named function expressions work on compliant implementations, but there used to be several bugs in implementations in the wild, most especially Internet Explorer 8 and earlier (and some early versions of Safari). IE8 processes a named function expresssion twice: First as a function declaration (upon entry into the execution context), and then later as a function expression, generating two distinct functions in the process. (Really.)
More here: Double take and here: Named function expressions demystified
NOTE: The below was written in 2011. In 2015, function declarations in control blocks were added to the language as part of ECMAScript 2015. Their semantics vary depending on whether you're in strict or loose mode, and in loose mode if the environment is a web browser. And of course, on whether the environment you're using has correct support for the ES2015 definition for them. (To my surprise, as of this writing in July 2017, Babel doesn't correctly transpile them, either.) Consequently, you can only reliably use function declarations within control-flow structures in specific situations, so it's still probably best, for now, to use function expressions instead.
And finally, another difference between them is where they're legal. A function expression can appear anywhere an expression can appear (which is virtually anywhere). A function declaration can only appear at the top level of its enclosing scope, outside of any control-flow statements. So for instance, this is valid:
function bar(x) {
var foo;
if (x) {
foo = function() { // Function expression...
// Do X
};
}
else {
foo = function() { // ...and therefore legal
// Do Y
};
}
foo();
}
...but this is not, and does not do what it looks like it does on most implementations:
function bar(x) {
if (x) {
function foo() { // Function declaration -- INVALID
// Do X
}
}
else {
function foo() { // INVALID
// Do Y
}
}
foo();
}
And it makes perfect sense: Since the foo function declarations are evaluated upon entry into the bar function, before any step-by-step code is executed, the interpreter has no idea which foo to evaluate. This isn't a problem for expressions since they're done during the control-flow.
Since the syntax is invalid, implementations are free to do what they want. I've never met one that did what I would have expected, which is to throw a syntax error and fail. Instead, nearly all of them just ignore the control flow statements and do what they should do if there are two foo function declarations at the top level (which is use the second one; that's in the spec). So only the second foo is used. Firefox's SpiderMonkey is the standout, it seems to (effectively) convert them into expressions, and so which it uses depends on the value of x. Live example.
I got an excellent explanation on this while asking very similar question: Two functions with the same name in JavaScript - how can this work?

Categories