javascript 创建函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5011776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript create function
提问by theHack
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:
另一个问题:在 PHP 中,我们通过这样做来创建一个函数:
function doSomething(a,b)
{
//do something to variable a and b...
}
In JavaScript, we may have an object before the function:
在 JavaScript 中,我们可能在函数之前有一个对象:
object.doSomething(a);
My second question is, how would you create a function which requires an object in JavaScript?
我的第二个问题是,您将如何创建一个需要 JavaScript 对象的函数?
回答by Wayne
The number one Google result for "function statement vs expression javascript" is another Stack Overflow question:
“函数语句与表达式 javascript”的排名第一的谷歌结果是另一个堆栈溢出问题:
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:
它引用了以下文章,这是该主题的权威参考:
回答by Aleksi Yrttiaho
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.
var fun = function() {}和之间的区别在于function fun() {},在第一种情况下,它存储在变量 中fun。要调用该函数,您必须调用fun(). 将它放在变量中可以让您传递函数。
You can create objects by using functions
您可以使用函数创建对象
function MyClass() {
this.fun = function() { alert('Hello world'); }
}
var obj = new MyClass();
obj.fun();
or JSON
或 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.
编辑。抱歉回答错误:人们不应该在凌晨 4 点尝试做这些事情。
回答by Jeff
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 hoistedto the top of your script.
从技术上讲,在这种情况下发生的是变量声明被提升到脚本的顶部。
回答by Ken Wayne VanderLinde
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.
这是函数文字如此有用的原因之一。

