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
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
This question already has answers here:
What does "this" mean in jQuery? [duplicate]
(6 answers)
Closed 7 years ago.
Reviewing some legacy code and saw it. The function body was done in pure Javascript without using any 3rd party library.
Could anyone shed a light on the use of "this" in (function() { })(this)?
Full codes:
(function() {
var root = this;
var SOMEVAR;
SOMEVAR = root.SOMEVAR = {};
SOMEVAR.windowOffset = 0;
SOMEVAR.defaultBase = 195;
SOMEVAR.resizeIFrame = function(){
// some codes
};
SOMEVAR.resetIFrameSize = function(height) {
// some codes
}
window.SOMEVAR = SOMEVAR;
})(this);
I actually read all "this" related usages before I asked the question. I just couldn't find this usage fits in those I read. And somehow, I don't think the "this" here is not even necessary because all the codes want is to create the "SOMEVAR" and bind it to "window". Am I correct?
Thanks
This is a somewhat weird example of an Immediately-Invoked Function Expression (IIFE). The first part:
(function(){})
simply defines a function (the outer parentheses are unnecessary). This function is then called, passing this as an argument. Usually one would actually declare a parameter and then do something to the parameter inside the function:
(function(context) {
// do something to or with context
})(this);
What object is actually referenced by this depends on where this code is executing and whether strict mode is in effect. See the docs for this for more information.
You're defining an anonymous function and then immediately invoking it with the this parameter.
If you're just looking to understand the meaning of this, then refer to this other question.
Ah, what is this. The oldest question in the javascript book. Generally speaking, this refers to the context that the current code is being executed in. If you have "top level" code being run straight in a script tag, it refers to window. In a click event? The current element. In a constructor? The object that will be constructed. You can even make it whatever you want with call and apply.
If you see this construct:
(function(ns) { })(this);
not inside other function then this is a reference of default namespace of script execution. In browsers that default namespace has quite strange name window therefore the following will output true:
(function(ns) {
console.log( ns === window );
})(this);
Such ns (namespace) variable is useful when you need for example check variable existence in namespace. This, for example:
alert(foo);
will rise an error "undefined variable foo", but this:
(function(ns) {
alert(ns.foo);
})(this);
will show alert with the word "undefined".
Another usage is in modules that can work as inside browser as in node.js and the like. Node.js has no notion of window so that construct above is the only reliable way to get reference to default namespace/scope object.
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) {}
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
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; }