What is the difference between this:
var doSomething=function()
{
//do blah blah blah...
}
And this:
function doSomething()
{
//do blah blah blah...
}
Another question: In PHP, we create a function by doing this:
function doSomething(a,b)
{
//do something to variable a and b...
}
In JavaScript, we may have an object before the function:
object.doSomething(a);
My second question is, how would you create a function which requires an object in JavaScript?
-
difference is that second function is defined at parse-time for a script block, whereas the first function is defined at run-timeKris Ivanov– Kris Ivanov2011年02月16日 02:11:50 +00:00Commented Feb 16, 2011 at 2:11
-
possible duplicate of var functionName = function() {} vs function functionName() {}Malachi– Malachi2015年07月13日 19:53:23 +00:00Commented Jul 13, 2015 at 19:53
4 Answers 4
The number one Google result for "function statement vs expression javascript" is another Stack Overflow question:
What is the difference between a function expression vs declaration in JavaScript?
It references the following article, which is the definitive reference on the subject:
1 Comment
The difference between var fun = function() {} and function fun() {} is that in the first case it is stored in the variable fun. To call the function, you have to call fun(). Having it in a variable lets you pass the function around.
You can create objects by using functions
function MyClass() {
this.fun = function() { alert('Hello world'); }
}
var obj = new MyClass();
obj.fun();
or JSON
var obj = {
fun: function() { alert('Hello world'); }
};
obj.fun();
You can further extend the objects or their prototypes with new functions.
Edit. Sorry for the wrong answer: one shouldn't try to do these kinds of things at 4 am.
6 Comments
undefined.One question at a time.
To answer your first question, there is not a huge difference.
function doSomething() {}
is technically equivalent to:
var doSomething;
doSomething = function() {};
technically what happens in this case is the variable declaration gets hoisted to the top of your script.
1 Comment
For the second part of the question, we just do something like
object.doSomething = function(a) { ... }
which is one reason the function literal is so useful.