Why there is "not a function" error if calling a function before function declaration with es6 syntax?

huangapple go评论75阅读模式
英文:

Why there is "not a function" error if calling a function before function declaration with es6 syntax?

问题

使用旧的语法

打印 "this is myfunc1"

myfunc1();

function myfunc1() {
console.log("this is myfunc1");
}

使用 ES6 语法
这会产生错误 "myfunc2 is not a function"

myfunc2();

var myfunc2 = () => {
  console.log("this is myfunc2");
}
英文:

Using older syntax

Prints "this is myfunc1"

myfunc1();

function myfunc1() {
console.log("this is myfunc1");
}

Using es6 syntax
This gives error "myfunc2 is not a function"

myfunc2();

var myfunc2 = () => {
  console.log("this is myfunc2");
}

答案1

得分: 2

Function declarations are hoisted.

使用 var 关键字进行的变量声明也会被提升(意味着 JavaScript 引擎“知道”变量已经声明),但是,因为赋值不会被提升,所以变量在执行赋值的代码行之前将包含 undefined


不要考虑这个 “旧” 和 “新” 语法。

函数声明、函数表达式和箭头函数都具有不同的行为。虽然箭头函数是最近引入到语言中的,但它们不能替代函数声明或函数表达式。

英文:

Function declarations are hoisted.

Variable declarations using var keyword are also hoisted (meaning the Javascript engine "knows" the variable has been declared) but, because assignments are not hoisted, the variable will contain undefined until the line of code that does the assignment is executed.


Do not consider this "old" and "new" syntax.

Function declarations, function expressions, and arrow functions all have different behaviour. While arrow functions were introduced to the language more recently, they are not a replacement for function declarations or function expressions.

huangapple
  • 本文由 发表于 2020年1月7日 00:16:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615447.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定