简体   繁体   English

JavaScript函数声明样式

[英]JavaScript Function declaration style

In Javascript, I have seen three different ways to define a function. 在Javascript中,我已经看到了三种不同的方法来定义函数。

  • Conventional style: 常规风格:

function foo() { //do something }

  • New Js Ninja Style 新Js忍者风格

var foo = function(){ //do something }

  • DOM specific style DOM特定的风格

window.foo = function(){ //do something }

What question is, 什么问题,

What is the difference between the above three? 以上三者有什么区别? And which one should I be using & why? 我应该使用哪一个?为什么?

The first one is function declaration. 第一个是功能声明。 It is hoisted (you could use it anywhere inside current scope). 它被悬挂(您可以在当前范围内的任何地方使用它)。

The second one is a variable definition using anonymous function. 第二个是使用匿名函数的变量定义。 Variable is hoisted, assignment stays in place. 变量悬挂,任务保持不变。 The function may not be used until the line where you assign it. 在您指定它的行之前,可能不会使用该函数。

The third one is assigning a global method. 第三个是分配全局方法。 Similar to the second one, although works with global object, which is not good. 与第二个类似,虽然适用于全局对象,但这并不好。

Yet, you could think about the fourth alternative(named function expression): 然而,你可以考虑第四种选择(命名函数表达式):

var foo = function bar(){ //do something }

Here, bar will be available only inside itself, which is useful for recursion and not churning current scope with it. 这里,bar只能在其自身内部使用,这对于递归非常有用,而不是用它来搅拌当前范围。

You are selecting any approach based on your needs. 您正在根据自己的需求选择任何方法。 I'd only vote against the second approach, as it makes function behave like a variable. 我只投票反对第二种方法,因为它使函数表现得像一个变量。

As soon as you mention both the second and the third option, I'd like to remind that polluting global object is considered bad practice . 一旦你提到第二个和第三个选项,我想提醒一下污染全球对象被认为是不好的做法 You'd better think about using self-executing anonymous functions to create separate scope, eg 您最好考虑使用自执行匿名函数来创建单独的范围,例如

(function(){
    var t = 42; // window.t still does not exist after that
})();

I suppose you may find a more detailed article on JavaScript Scoping and Hoisting useful. 我想你可能会发现一篇关于JavaScript范围和提升的更详细的文章。

First, see Javascript: var functionName = function() {} vs function functionName() {} . 首先,请参阅Javascript:var functionName = function(){} vs function functionName(){}

Then we get to the difference between var foo = and window.foo = . 然后我们得到var foo =window.foo =之间的区别。

The first is a locally scoped variable which is nice and lovely (unless it is done in the global scope). 第一个是本地范围的变量,它很好很可爱(除非它在全局范围内完成)。 The second is a an explicit global, which has all the usual issues of globals (such as likelihood of conflicting with other code). 第二个是显式全局,它具有全局变量的所有常见问题(例如与其他代码冲突的可能性)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM