英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论