Why JavaScript function declaration (and expression)? - javascript

I've seen others using the following pattern.
var bar = function foo(){};
console.log(bar); // foo()
console.log(foo); // ReferenceError: foo is not defined
But why? I can see the point if both were declared, but they're not. Why is the reason?

As mentioned by others, using the first form in your example (a named function expression) can help with debugging, although with the recent improvements in built-in developer tools in browsers, this argument is becoming less persuasive. The other reason for using a named function expression is that you can use the function name as a variable within the body of the function rather than the now-deprecated in ES5 arguments.callee.
However, named function expressions are incorrectly and problematically implemented in Internet Explorer < 9 and should generally be avoided when you're targeting those browsers. See Juriy Zaytsev's excellent article on the subject for more information.

When debugging an application, it is easier to know what is calling what in the call stack when "named" anonymous functions are used. So it is a way to give a name to an anonymous function for debugging purposes.
Try this and look at the callstack in a debugger:
myDiv = document.getElementById("myDiv");
myDiv.onclick = function OnClick(){
debugger;
//do something
}

They are naming an anonymous function because it makes debugging easier. When debugging, you will see a call to "foo" in the call stack rather than a bunch of calls to "anonymous".

The only reason I can imagine for this is to give the function a desired name. This helps debugging as the inspector uses the function object's name attribute. Try this:
var bar = function foo(){};
console.log(bar.name); // foo
If you put some real code inside foo and add a breakpoint to the JavaScript debugger in your browser, you will see the function as foo in the call stack.

The function definition (or literal) has 4 parts. 1. The reserved word function 2. An optional name which can be used by debuggers or by the function to call itself recursively. 3. The parameters and 4. The body of the function wrapped by { }
Outside of the function scope foo doesn't exist. But since you assigned the function to the variable bar you can call it using the method invocation bar and since bar is defined you can print it.
If you're interested in JavaScript you should really consider getting Douglas Crockford's book Javascript: The Good Parts

Related

Javascript named function assigned to a property

I'm working on some JavaScript code that defines some class methods by defining the prototype object, as shown below:
/**
* #constructor
*/
function MyClass() {
var someField = 'hello world';
}
MyClass.prototype = {
getSomeField1: function getSomeField2() {
return someField;
}
};
I have two questions:
What is getSomeField2, and will it be accessible to any code?
Can anyone give any examples of a scenario where it might be advantageous to use different names for the key and for the function name? I would have thought it would just confuse people reading the code.
In all other instances of similar code, either the property and the function names match, or the function is unnamed.
The main benefit is that all browsers will show names of functions in stack traces.
Typically, people use an anonymous function when assigning it to a property or variable. Chrome had been pretty good at figuring out that it should use the property or variable name on the stack trace, but IE used to show anonymous.
Also named functions have a name property
(function a(){}).name // a
(function(){}).name // ""
Naming functions is useful for debugging. When printing a stack trace, for instance, the name getSomeField2 will show up, instead of "Anonymous Function". It's also useful for defining recursive functions, as there's no other clear way for a function to call itself. Before named function expressions were introduced in JS, if a function wanted to call itself was by using the (rather ugly and "forbidden" since ES5) arguments.callee approach.
So, to answer your question, the getSomeField2 binding is only available inside the function body, which you can verify as follows:
(function myFunctionName() {
console.log(`Inside: ${myFunctionName}`); // prints the function body
})();
console.log(`Outside: ${myFunctionName}`); // ReferenceError: myFunctionName is not defined

scope of JS code in chroome [duplicate]

I've seen others using the following pattern.
var bar = function foo(){};
console.log(bar); // foo()
console.log(foo); // ReferenceError: foo is not defined
But why? I can see the point if both were declared, but they're not. Why is the reason?
As mentioned by others, using the first form in your example (a named function expression) can help with debugging, although with the recent improvements in built-in developer tools in browsers, this argument is becoming less persuasive. The other reason for using a named function expression is that you can use the function name as a variable within the body of the function rather than the now-deprecated in ES5 arguments.callee.
However, named function expressions are incorrectly and problematically implemented in Internet Explorer < 9 and should generally be avoided when you're targeting those browsers. See Juriy Zaytsev's excellent article on the subject for more information.
When debugging an application, it is easier to know what is calling what in the call stack when "named" anonymous functions are used. So it is a way to give a name to an anonymous function for debugging purposes.
Try this and look at the callstack in a debugger:
myDiv = document.getElementById("myDiv");
myDiv.onclick = function OnClick(){
debugger;
//do something
}
They are naming an anonymous function because it makes debugging easier. When debugging, you will see a call to "foo" in the call stack rather than a bunch of calls to "anonymous".
The only reason I can imagine for this is to give the function a desired name. This helps debugging as the inspector uses the function object's name attribute. Try this:
var bar = function foo(){};
console.log(bar.name); // foo
If you put some real code inside foo and add a breakpoint to the JavaScript debugger in your browser, you will see the function as foo in the call stack.
The function definition (or literal) has 4 parts. 1. The reserved word function 2. An optional name which can be used by debuggers or by the function to call itself recursively. 3. The parameters and 4. The body of the function wrapped by { }
Outside of the function scope foo doesn't exist. But since you assigned the function to the variable bar you can call it using the method invocation bar and since bar is defined you can print it.
If you're interested in JavaScript you should really consider getting Douglas Crockford's book Javascript: The Good Parts

Is there another way to write a function declaration?

It just seems odd to me to write dbr.onsuccess after dbr has been declared.
var dbr = window.indexedDB.open("Matrix");
dbr.onsuccess = function(myEvent) {}
Q: Is there an alternative way to write line 2 (without being Rube Goldberg)? Maybe something like:
function dbr.onsuccess(myEvent) {
}
I'm just concerned about the order of things. To me, it seems that it's too late to assign an onsuccess function to dbr after it's been created.
var dbr = window.indexedDB.open("Matrix");
is an asynchronous request.
Async requests run in the background and won't run their callbacks until the function completes. So all of the other assignments will happen before any callback functions are run.
The indexedDB is returning you an interface object so that you can define exactly what those callback functions are. You can think of it as you making a request
Hey I want to open matrix
and getting a response back saying
Hey, I'm working on that, here's an object. Please list what you want to have happen when I finish on it.
Then, when it has completed the open operation (and the current function context has completed running) it will look at that object and run accordingly.
The return value of open isn't the real result of the function, its just an object returned for you to tell it what to do. This is similar to a promise/deferred way of doing things, which is different from the normal JS callback model.
This:
function dbr.onsuccess(myEvent) {
}
is not valid syntax. You can't define a property on an object till the object itself has been defined, and javascript doesn't support function declarations for properties. They're only used for top level objects.
dbr.onsuccess = function(myEvent) {}
This is technically a function expression, as it's an assignment statement to the onsuccess property of dbr.
So when you ask if there is more than one way to write a function declaration, the answer is technically no.
A function declaration has only one form:
function foo() {}
Your suggested syntax to declare a function as a property of an object is interesting but a wrinkle in the idea is function hoisting. As you probably already know, functions (including their definitions) available anywhere within scope, even preceding code. Take this example:
foo.bar();
var foo = getFoo();
function foo.bar() {}
Due to function hoisting, foo.bar should be available on line 1. But due to variable hoisting, foo is declared but not yet defined. On line 1 foo has a value of undefined and would result in a TypeError if you tried to invoke function foo.bar.
I think you can say:
var dbr = window.indexedDB.open("Matrix").onsuccess = function(myEvent) {}

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