正确使用 const 定义函数 [英] Proper use of const for defining functions

查看:40
本文介绍了正确使用 const 定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中使用 const 可以设置哪些类型的值,尤其是函数,是否有任何限制?这是有效的吗?诚然它确实有效,但出于任何原因,这是否被认为是不好的做法?

Are there any limits to what types of values can be set using const in JavaScript, and in particular, functions? Is this valid? Granted it does work, but is it considered bad practice for any reason?

const doSomething = () => {
   ...
}

ES6 中的所有函数都应该这样定义吗?如果是这样的话,这似乎并没有流行起来.

Should all functions be defined this way in ES6? It does not seem like this has caught on, if so.

推荐答案

你所做的没有问题,但你必须记住函数声明和函数表达式之间的区别.

There's no problem with what you've done, but you must remember the difference between function declarations and function expressions.

一个函数声明,即:

function doSomething () {}

完全提升到作用域的顶部(并且像 letconst 它们也是块作用域).

Is hoisted entirely to the top of the scope (and like let and const they are block scoped as well).

这意味着以下内容将起作用:

This means that the following will work:

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.

因此,在范围内变量提升的通常规则——块范围变量(letconst)不会作为 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 定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆