在 JavaScript 中声明函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1925976/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:55:39  来源:igfitidea点击:

Declaring functions in JavaScript

javascriptsyntaxfunction

提问by nicholaides

Possible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}

可能的重复:
Javascript:var functionName = function() {} vs function functionName() {}

What's the difference between these two ways of declaring a function?

这两种声明函数的方式有什么区别?

function someFunc() { ... }

var someFunc = function() { ... }

I'm not asking in the technical sense. I'm not asking which is better for readability, or which style is preferred.

我不是在技术意义上问。我不是在问哪种更便于阅读,或者哪种风格更受欢迎。

采纳答案by Priyank

I am on different opinion with most of the people here. Technically this syntax may mean the same for declaring functions both ways(I stand incorrect on my last statement. I read up on a diff post why they are technically diff and I'll add in the end, why) ; but the way they play a role in evolving patterns is massive. I would highly recommend "Javascript: The Good Parts" by Doughlas Crockford.

我和这里的大多数人意见不同。从技术上讲,这种语法对于双向声明函数可能意味着相同我对我的最后一条语句的立场不正确。我阅读了一篇 diff 帖子,为什么它们在技术上是不同的,最后我会添加,为什么);但它们在进化模式中发挥作用的方式是巨大的。我强烈推荐 Doughlas Crockford 的“Javascript: The Good Parts”。

But to prove my point in a subtle and a simple manner; here is a small example.

但要以一种微妙而简单的方式证明我的观点;这是一个小例子。

//Global function existing to serve everyone
function swearOutLoud(swearWord) {
    alert("You "+ swearWord);           
}
//global functions' territory ends here

//here is mr. spongebob. He is very passionate about his objects; but he's a bit rude.
var spongeBob = {
    name : "squarePants",
    swear : function(swearWord) {
                name = "spongy";
                alert("You "+ swearWord);
                return this;
            }
}

//finally spongebob learns good manners too. EVOLUTION!
spongeBob.apologize = function() {
    alert("Hey " + this.name + ", I'm sorry man!");
    return this;
}


//Ask spongebob to swear and then apologize in one go (CASCADING EFFECT!!)
alert(spongeBob.swear("twit").apologize());

if you look at the code above I declared a function with a name swearOutLoud. Which would take a swear word from any object or a call and will give you the output. It can do operations on any object using the "this" parameter that is passed to it and the arguments.

如果您查看上面的代码,我声明了一个名为 swearOutLoud 的函数。这将从任何对象或电话中获取脏话,并为您提供输出。它可以使用传递给它的“this”参数和参数对任何对象进行操作。

However second declaration is declared as an attribute of object called "spongeBob". This is important to note; as here I am moving towards an object driven behavior. While I am also maintaining "cascading effect" as I return "this" if i have nothing else to return.

然而,第二个声明被声明为名为“spongeBob”的对象的属性。需要注意这一点很重要;在这里,我正朝着对象驱动的行为迈进。虽然我也保持“级联效应”,因为如果我没有其他东西可以返回,我会返回“这个”。

Somthing similar is done in jquery; and this cascading pattern is important if you are trying to write a framework or something. You'll link it to Builder design pattern also.

在 jquery 中做了类似的事情;如果您正在尝试编写框架或其他东西,这种级联模式很重要。您还将把它链接到 Builder 设计模式。

But with functions declared as an attributes of an object I am able to achieve an object centric behavior which leads to a better programming paradigm. Unless designed well; individual functions declared outside with global access lead to a non-object oriented way of coding. I somehow prefer the latter.

但是通过将函数声明为对象的属性,我能够实现以对象为中心的行为,从而产生更好的编程范式。除非设计得很好;在外部声明的具有全局访问权限的单个函数导致了一种非面向对象的编码方式。不知何故,我更喜欢后者。

To see cascading in effect, look at the last statement where you can ask spongebob to swear and apologize at once; even though apologize was added as an attribute later on.

要查看级联效果,请查看最后一个语句,您可以在其中要求海绵宝宝立即发誓并道歉;即使道歉是后来作为属性添加的。

I hope I make my point clear. The difference from a technical perspective may be small; but from design and code evolution perspective it's huge and makes a world of a difference.

我希望我说清楚我的观点。从技术角度来看,差异可能很小;但从设计和代码演变的角度来看,它是巨大的,并且使世界变得不同。

But thats just me! Take it or leave it. :)

但这只是我!要么接受,要么离开它。:)

EDIT:

编辑:

So both the calls are technically different; because a named declaration is tied to global namespace and is defined at parse time. So can be called even before the function is declared.

所以这两个调用在技术上是不同的;因为命名声明与全局命名空间相关并在解析时定义。所以甚至可以在声明函数之前调用。

 //success
 swearOutLoud("Damn");

function swearOutLoud(swearWord) {
    alert("You " + swearWord)
}

Above code will work properly. But code below will not.

上面的代码将正常工作。但下面的代码不会。

swear("Damn!");
    var swear = function(swearWord) {
    console.log(swearWord);
}

回答by Igor Zevaka

One advantage of using function someFunc() { ... }is that the function name appears in Firebug debugger. Functions that are declared the other way (var someFunc = function() { ... }) come up as anonymous.

使用的好处之一function someFunc() { ... }是函数名出现在 Firebug 调试器中。以另一种方式 ( var someFunc = function() { ... })声明的函数作为匿名函数出现。

回答by Soufiane Hassou

Actually, the difference is that the second declaration gives us the ability to declare functions like this making it possible to have a function as a property for an object :

实际上,不同之处在于第二个声明使我们能够像这样声明函数,从而可以将函数作为对象的属性:

var myObject=new Object();
myObject.someFunc=function() { ... }; 

回答by frglps

Style wise the second example is more consistent with other common ways to declare functions and therefore it could be argued that it is more readable

风格明智的第二个例子与其他常见的函数声明方式更一致,因此可以说它更具可读性

this.someFunc = function() { ... }
...
someFunc: function() { ... },

However, as also mentioned it's anonymous and therefore the name does not appear when profiling. Another way to declare the function is as follows which gets you the best of both worlds

但是,正如也提到的,它是匿名的,因此在分析时不会出现该名称。声明函数的另一种方法如下,它可以让你两全其美

var someFunc = function someFunc() { ... }

回答by outis

Another difference is that, on most browsers, the latter allows you to define different implementations depending on circumstances, while the former won't. Say you wanted cross-browser event subscription. If you tried to define a addEventListenerTofunction thusly:

另一个区别是,在大多数浏览器上,后者允许您根据情况定义不同的实现,而前者则不允许。假设您想要跨浏览器事件订阅。如果你试图这样定义一个addEventListenerTo函数:

if (document.addEventListener) {
    function addEventListenerTo(target, event, listener) {
        ....
    }
} else if (document.attachEvent) {
    function addEventListenerTo(target, event, listener) {
        ....
    }
} else {
    function addEventListenerTo(target, event, listener) {
        ....
    }
}

on some browsers, all the functions end up being parsed, with the last one taking precedence. Result: the above just doesn't work. Assigning anonymous functions to variables, however, will work. You can also apply functional and basic aspect oriented programmingtechniques using anonymous functions assigned to variables.

在某些浏览器上,所有函数最终都会被解析,最后一个优先。结果:上述方法不起作用。但是,将匿名函数分配给变量是可行的。您还可以使用分配给变量的匿名函数来应用函数式和基本面向方面的编程技术。

var fib = memoize(function (n) { 
    if (n < 0) return 0;
    if (n < 2) return 1;
    return fib(n-1) + fib(n-2); 
});

...
// patch the $ library function
if (...) {
    $ = around($, fixArg, fixResult);
}

回答by EMK

It is both true that the first form:

第一种形式是正确的:

function test() { }

is a more recognized syntax and that the second form:

是一种更受认可的语法,第二种形式:

var test = function() { ... }

allows you to control the scope of the function (through the use of var; without it, it would be global anyway).

允许您控制函数的范围(通过使用 var;没有它,无论如何它都是全局的)。

And you can even do both:

您甚至可以同时执行以下两项操作:

var test = function test() { ... test(); ... }

This allows you to define a recursive function in the second form.

这允许您以第二种形式定义递归函数。

回答by Paul Degnan

For readability, I'd say the first is clearly better. A future maintenance programmer, even assuming they're familiar enough with javascript to know many of the finer points coming up in this thread, are going to assume the first format.

为了可读性,我想说第一个显然更好。未来的维护程序员,即使假设他们对 javascript 足够熟悉,知道这个线程中出现的许多细节,也会假设第一种格式。

For example, if they should some day want to ctrl-f to search for the definition of your function to see what's happening in there, are they going to first search for someFunc = function()or function someFunc()?

例如,如果他们有一天想要按 ctrl-f 来搜索您的函数的定义以查看其中发生了什么,他们会首先搜索someFunc = function()function someFunc()吗?

Also, to get downright typographical about it (since we're talking readablity) readers are often scanning the text quickly, and would be more inclined to skip over a line that starts with "var" if they're looking for a function definition.

此外,为了获得彻底的排版(因为我们在谈论可读性),读者通常会快速浏览文本,并且如果他们正在寻找函数定义,则更倾向于跳过以“var”开头的行。

I know this is a non-technical answer, but it's harder for humans to read code than computers.

我知道这是一个非技术性的答案,但人类阅读代码比计算机更难。

回答by kiamlaluno

When you write

当你写

function Test() {
}

JavaScript is really creating a property to which it assigns the function object that once called will execute the code reported in the function definition. The property is attached to the object window, or to the object that contains the function definition.

JavaScript 实际上是在创建一个属性,它将函数对象分配给该属性,该函数对象一旦调用将执行函数定义中报告的代码。该属性附加到对象window,或附加到包含函数定义的对象。