【发布时间】: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