What is the difference between this:
var do开发者_Python百科Something=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?
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:
http://kangax.github.com/nfe/
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.
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.
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.
精彩评论