【问题标题】:Is there a difference between a function and an arrow (=>) function函数和箭头 (=>) 函数之间有区别吗
【发布时间】:2019-08-09 13:14:03
【问题描述】:

我一直在玩 ES6 的特性有一段时间了,就在这个场合,我在声明它之前使用该函数时出现错误,但是当我改用旧的传统方式时,错误没有被捕获.

函数提升是否仅适用于传统方式,还是我缺少一个问题?

我尝试过搜索,但这个Besides syntax, is there any difference between a normal function and an arrow function? 无法给我一个满意的结果

一个简单的输入表单代码:

<!DOCTYPE html>
<html>
<head>
  <title>Hero Form</title>
</head>
<body>
  <form id="hero">
    <label for="heroName">Name:
      <input type="text" name="heroName" autofocus
      placeholder="Your super Hero Name"Smaxlength="32">
    <!-- </label> -->
    <button id="submit" type="submit">Submit</button>
  </form>
</body>
</html>
<script>
  // Throws an error when called first
  form.addEventListener('submit', makeHero, false);
  const form = document.forms.hero;

  const makeHero = (event) => {
    event.preventDefault();
    const hero = {};
    hero.name = form.heroName.value;
    console.log(JSON.stringify(hero), hero, 'clear');
    return hero;
  }
</script>
<script>
  const form = document.forms.hero;

  const makeHero = (event) => {
    event.preventDefault();
    const hero = {};
    hero.name = form.heroName.value;
    console.log(JSON.stringify(hero), hero, 'clear');
    return hero;
  }
// Works fine after arrow function declaration
  form.addEventListener('submit', makeHero, false);
</script>

【问题讨论】:

  • 箭头函数没有被提升,所以你需要把form.addEventListener('submit', makeHero, false);放在底部。
  • 箭头函数显然只是分配给常规变量的值。另一方面,function 声明是一种完全不同的声明,它们被提升了。
  • “函数提升是否只适用于传统方式,还是我错过了一个问题?” — 您已经证明函数声明被提升,而箭头函数赋值给常量则没有。不清楚您为什么觉得有必要提出这个问题。

标签: javascript ecmascript-6 hoisting


【解决方案1】:

这实际上与箭头函数本身无关。在 JavaScript 中,声明被提升到其作用域的顶部。声明可能如下所示:

let x = 42;

但是,这个单一的语句实际上做了两件事。一、声明:

let x

然后是作业:

x = 42

在这里,声明(let x)被提升,但不是赋值x = 42)。

这与您对变量声明所做的操作与您将变量分配给箭头函数所做的操作没有什么不同:

const makeHero = (event) => { ...

const makeHero 将被提升,但不会分配:`makeHero = (event) => { ...

函数可以通过不止一种方式设置,其中一种方式是Function Declaration,它不分配变量并且整个函数被提升:

function makeHero(event) {
}

现在 Function Expression 只是一个表达式,其中函数被分配为其他值的值,这就是您将箭头函数分配给常量 hero 所做的事情。所以,const hero 被提升,但不是分配,所以如果你在分配之前尝试调用 hero,你会得到一个错误。

【讨论】:

    猜你喜欢
    • 2016-01-25
    • 2020-05-07
    • 2010-09-05
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    相关资源
    最近更新 更多