var functionName = function(){} vs function functionName(){} [英] var functionName = function() {} vs function functionName() {}

查看:191
本文介绍了var functionName = function(){} vs function functionName(){}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始维护别人的JavaScript代码。我修正了错误,增加了功能,并试图整理代码并使其更加一致。

前面的开发人员使用两种声明函数的方法,我可以'如果有背后的原因,那么就算出来。



两种方法是:

  var functionOne = function(){
//一些代码
};





  function functionTwo() {
//一些代码
}

使用这些的原因是什么两种不同的方法,每种方法的优缺点是什么?有什么可以用另一种方法完成的吗?

解决方案

不同之处在于 functionOne 是一个函数表达式,所以只在到达该行时才被定义,而 functionTwo 是一个函数声明并被定义为一旦其周围的函数或脚本被执行(由于提升 )。



例如,一个函数表达式:

  // TypeError:undefined不是functionfunctionOne(); var functionOne = function(){console.log(Hello!);};   

和一个函数声明:

  //输出:Hello!functionTwo(); function functionTwo(){console.log(Hello!);}  



这也意味着你不能使用函数声明有条件地定义函数: b
$ b

  if(test){
//错误或行为不当
函数functionThree(){doSomething(); }
}

上面实际上定义了 functionThree 不论 test 的值 - mdash;除非 use strict 有效,在这种情况下,它只会产生一个错误。


I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.

The previous developer uses two ways of declaring functions and I can't work out if there is a reason behind it or not.

The two ways are:

var functionOne = function() {
    // Some code
};

function functionTwo() {
    // Some code
}

What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?

解决方案

The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).

For example, a function expression:

// TypeError: undefined is not a function
functionOne();

var functionOne = function() {
  console.log("Hello!");
};

And, a function declaration:

// Outputs: "Hello!"
functionTwo();

function functionTwo() {
  console.log("Hello!");
}

This also means you can't conditionally define functions using function declarations:

if (test) {
   // Error or misbehavior
   function functionThree() { doSomething(); }
}

The above actually defines functionThree irrespective of test's value — unless use strict is in effect, in which case it simply raises an error.

这篇关于var functionName = function(){} vs function functionName(){}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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