var name = function(){}&和var之间有什么区别吗? Javascript中的函数名称(){}? [英] Is there any difference between var name = function() {} & function name() {} in Javascript?

查看:105
本文介绍了var name = function(){}&和var之间有什么区别吗? Javascript中的函数名称(){}?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

JavaScript:var functionName = function(){} vs function functionName(){}

假设我们在函数内而不在全局命名空间中。

Suppose we are inside a function and not in the global namespace.

function someGlobalFunction() {
  var utilFunction1 = function() {
  }

  function utilFunction2 () {
  }

  utilFunction1();
  utilFunction2();

}

这些是同义词吗?当 someGlobalFunction 返回时,这些函数是否完全不存在?我是否因为可读性或其他原因而更喜欢其中一种?

Are these synonymous? And do these functions completely cease to exist when someGlobalFunction returns? Should I prefer one or the other for readability or some other reason?

推荐答案

他们主要是同样。

utilFunction1 只有在声明后才可用。 utilFunction2 被提升到函数顶部,因此可以在定义之前使用。

utilFunction1 will only be available after it has been declared. utilFunction2 is hoisted to the top of the function, so can be used before it is defined.

function someGlobalFunction() {
  utilFunction1(); // Error: untilFunction1 is undefined :(
  utilFunction2(); // Works

  var utilFunction1 = function() {
  }

  function utilFunction2 () {
  }
}

除非它们被困在一个闭包中,当 someGlobalFunction 返回时,两者都将不复存在。

Unless they are trapped in a closure, both will cease to exist when someGlobalFunction returns.

我更喜欢使用用于声明<$ c $的方法c> utilFunction2 ,但这取决于你。

I prefer to use the method used to declare utilFunction2, but it's up to you.

表格的声明 utilFunction2 (它们被称为函数声明)具有在 your-favorite-debugger TM中命名(即显示为 utilFunction2 )的好处。 ,其中 utilFunction1 (称为函数表达式)只会显示为匿名函数

Declarations of the form utilFunction2 (which are called Function Declarations) have the benefit of being named (i.e. showing up as utilFunction2) in your-favourite-debuggerTM, where as utilFunction1 (called Function Expressions) would just show up as an anonymous function.

为完整起见,您还有表格;

For completeness, you also have the form;

var utilFunction3 = function utilFunction4() {
    // blah
};

...这被称为名为的函数表达式,其中包含奇怪的属性(和错误(在较旧版本中)自己的IE))版本。

... which is called a named function expression, which has weird properties (and bugs (in older versions of IE)) of its own.

这篇关于var name = function(){}&amp;和var之间有什么区别吗? Javascript中的函数名称(){}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆