正确使用const来定义JavaScript中的函数 [英] Proper use of const for defining functions in JavaScript
问题描述
如果在JavaScript中使用 const
在特定功能中可以设置什么类型的值,我感兴趣。这是否有效?确定它有效,但是由于任何原因它被认为是不好的做法?
I am interested if there are any limits to what types of values can be set using const
in JavaScript—in particular functions. Is this valid? Granted it does work, but is it considered bad practice for any reason?
const doSomething = () => {
...
}
ES6?
感谢任何评论!
推荐答案
你做了什么没有问题,但你必须记住函数声明和函数表达式之间的区别。
There's no problem with what you've done, but you must remember the difference between function declarations and function expressions.
函数声明,那就是:
function doSomething () {}
完全悬挂在范围的顶部(如 let
和 const
他们也是框架范围)。
Is hoisted entirely to the top of the scope (and like let
and const
they are block scoped as well).
这意味着以下工作:
doSomething() // works!
function doSomething() {}
一个函数表达式,即:
[const | let | var] = function () {} (or () =>
创建匿名函数( function(){}
)和创建变量,然后将该匿名函数分配给该变量。
Is the creation of an anonymous function (function () {}
) and the creation of a variable, and then the assignment of that anonymous function to that variable.
所以在范围内的变量提升的通常规则 - 块范围变量( let
和 const
)不要将 undefined
提升到块范围的顶部。
So the usual rules around variable hoisting within a scope -- block-scoped variables (let
and const
) do not hoist as undefined
to the top of their block scope.
这意味着:
if (true) {
doSomething() // will fail
const doSomething = function () {}
}
将失败,因为 doSomething
没有定义(它会抛出一个 ReferenceError
)
Will fail since doSomething
is not defined. (It will throw a ReferenceError
)
如果切换到使用 var
你可以得到你的变量的提升,但是它将被初始化为 undefined
,以便上面的代码块仍然不起作用(这将抛出一个 TypeError
自 doSomething
在您调用时不是一项功能)
If you switch to using var
you get your hoisting of the variable, but it will be initialized to undefined
so that block of code above will still not work. (This will throw a TypeError
since doSomething
is not a function at the time you call it)
就标准做法而言,您应该永远使用正确的工具作为工作。
As far as standard practices go, you should always use the proper tool for the job.
Axel Rauschmayer在范围和提升方面有一个很棒的职位,包括es6语义: ES6中的变量和范围设置
Axel Rauschmayer has a great post on scope and hoisting including es6 semantics: Variables and Scoping in ES6
这篇关于正确使用const来定义JavaScript中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!