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

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

问题描述

我最近开始维护别人的 JavaScript 代码.我正在修复错误、添加功能并尝试整理代码并使其更加一致.

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 used two ways of declaring functions and I can't work out if there is a reason behind it or not.

两种方式是:

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?

推荐答案

区别在于 functionOne 是一个函数表达式,因此只在到达该行时定义,而 functionTwo 是一个函数声明,并在其周围的函数或脚本执行后立即定义(由于 提升).

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).

例如一个函数表达式:

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

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

还有,一个函数声明:

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

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

过去,块中定义的函数声明在浏览器之间的处理不一致.严格模式(在 ES5 中引入)通过将函数声明范围限定到它们的封闭块来解决这个问题.

Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block.

'use strict';    
{ // note this block!
  function functionThree() {
    console.log("Hello!");
  }
}
functionThree(); // ReferenceError

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

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