在JavaScript中使用const可以设置什么类型的值,特别是函数,有任何限制吗?这有效吗?当然,它确实有效,但出于某种原因,它被认为是一种坏做法吗?

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

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


当前回答

使用const有一些非常重要的好处,有些人会说应该在任何可能的地方使用它,因为它是非常慎重和指示性的。

据我所知,它是JavaScript中最具指示性和可预测性的变量声明,也是最有用的变量声明之一,因为它的约束程度很高。为什么?因为它消除了var和let声明的一些可能性。

当你读取const时,你能推断出什么?你只需要阅读const声明语句就可以知道以下所有内容,并且不需要扫描对该变量的其他引用:

值被绑定到该变量(尽管它的底层对象不是深度不可变的) 它不能在其直接包含块的外部访问 由于临时死区(TDZ)规则,在声明之前永远不会访问绑定。

以下引文摘自一篇讨论let和const优点的文章。它也更直接地回答了你关于关键字的约束/限制的问题:

Constraints such as those offered by let and const are a powerful way of making code easier to understand. Try to accrue as many of these constraints as possible in the code you write. The more declarative constraints that limit what a piece of code could mean, the easier and faster it is for humans to read, parse, and understand a piece of code in the future. Granted, there’s more rules to a const declaration than to a var declaration: block-scoped, TDZ, assign at declaration, no reassignment. Whereas var statements only signal function scoping. Rule-counting, however, doesn’t offer a lot of insight. It is better to weigh these rules in terms of complexity: does the rule add or subtract complexity? In the case of const, block scoping means a narrower scope than function scoping, TDZ means that we don’t need to scan the scope backwards from the declaration in order to spot usage before declaration, and assignment rules mean that the binding will always preserve the same reference. The more constrained statements are, the simpler a piece of code becomes. As we add constraints to what a statement might mean, code becomes less unpredictable. This is one of the biggest reasons why statically typed programs are generally easier to read than dynamically typed ones. Static typing places a big constraint on the program writer, but it also places a big constraint on how the program can be interpreted, making its code easier to understand. With these arguments in mind, it is recommended that you use const where possible, as it’s the statement that gives us the least possibilities to think about.

来源:https://ponyfoo.com/articles/var-let-const

其他回答

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

函数声明,即:

function doSomething () {}

完全提升到作用域的顶部(与let和const一样,它们也是块作用域)。

这意味着以下将起作用:

doSomething() // works!
function doSomething() {}

一个函数表达式,即:

[const | let | var] = function () {} (or () =>

是创建一个匿名函数(function(){})和创建一个变量,然后将该匿名函数赋值给该变量。

因此,在作用域内提升变量的通常规则——块作用域变量(let和const)不会将未定义的变量提升到其块作用域的顶部。

这意味着:

if (true) {
    doSomething() // will fail
    const doSomething = function () {}
}

将失败,因为doSomething未定义。(它会抛出一个ReferenceError)

如果你切换到使用var,你得到了变量的提升,但它将被初始化为未定义,所以上面的代码块仍然不能工作。(这将抛出一个TypeError,因为doSomething在你调用它的时候不是一个函数)

就标准实践而言,您应该始终使用合适的工具来完成这项工作。

Axel Rauschmayer有一篇关于范围和提升的很棒的文章,包括es6语义:变量和es6中的范围

使用const有一些非常重要的好处,有些人会说应该在任何可能的地方使用它,因为它是非常慎重和指示性的。

据我所知,它是JavaScript中最具指示性和可预测性的变量声明,也是最有用的变量声明之一,因为它的约束程度很高。为什么?因为它消除了var和let声明的一些可能性。

当你读取const时,你能推断出什么?你只需要阅读const声明语句就可以知道以下所有内容,并且不需要扫描对该变量的其他引用:

值被绑定到该变量(尽管它的底层对象不是深度不可变的) 它不能在其直接包含块的外部访问 由于临时死区(TDZ)规则,在声明之前永远不会访问绑定。

以下引文摘自一篇讨论let和const优点的文章。它也更直接地回答了你关于关键字的约束/限制的问题:

Constraints such as those offered by let and const are a powerful way of making code easier to understand. Try to accrue as many of these constraints as possible in the code you write. The more declarative constraints that limit what a piece of code could mean, the easier and faster it is for humans to read, parse, and understand a piece of code in the future. Granted, there’s more rules to a const declaration than to a var declaration: block-scoped, TDZ, assign at declaration, no reassignment. Whereas var statements only signal function scoping. Rule-counting, however, doesn’t offer a lot of insight. It is better to weigh these rules in terms of complexity: does the rule add or subtract complexity? In the case of const, block scoping means a narrower scope than function scoping, TDZ means that we don’t need to scan the scope backwards from the declaration in order to spot usage before declaration, and assignment rules mean that the binding will always preserve the same reference. The more constrained statements are, the simpler a piece of code becomes. As we add constraints to what a statement might mean, code becomes less unpredictable. This is one of the biggest reasons why statically typed programs are generally easier to read than dynamically typed ones. Static typing places a big constraint on the program writer, but it also places a big constraint on how the program can be interpreted, making its code easier to understand. With these arguments in mind, it is recommended that you use const where possible, as it’s the statement that gives us the least possibilities to think about.

来源:https://ponyfoo.com/articles/var-let-const

虽然使用const来定义函数看起来像是一种hack,但它带来了一些很大的优势,使其更优越(在我看来)

它使函数不可变,所以你不必担心函数会被其他代码段改变。 你可以使用胖箭头语法,它更简洁。 使用箭头函数可以为您处理这个绑定。

函数示例

定义一个函数 函数add(x, y){返回x + y;} //使用它 console.log(添加(1、2);/ / 3 //哎呀,有人改变了你的函数 Add = function (x, y){返回x - y;}; //这不是你所期望的 console.log(添加(1、2);/ / 1

const的例子也一样

//定义函数(哇!短了8个字符) Const add = (x, y) => x + y; //使用它 console.log(添加(1、2);/ / 3 //某人试图改变函数 Add = (x, y) => x - y;//未捕获的类型错误:赋值给常量变量。 //入侵者失败,你的函数保持不变

这个问题已经问了三年了,我现在才突然想到。由于这个答案是如此之远,请允许我重复一遍:

问:我感兴趣的是价值观的类型是否有限制 在javascript中使用const设置—在特定的函数中。这有效吗? 当然它确实有效,但它是否被认为是一种坏习惯 原因吗?

在观察到一个多产的JavaScript程序员总是在函数中使用const语句,即使没有明显的理由/好处,我也被激励着做一些研究。

在回答“它是否被认为是一种不好的做法?”时,让我说,在我看来,是的,或者至少,使用函数语句是有好处的。

在我看来,这在很大程度上是一个偏好和风格的问题。上面有一些很好的论点,但没有一个像本文中所做的那样清楚: 不断的困惑:为什么我仍然使用JavaScript函数语句medium.freecodecamp.org/Bill Sourour, JavaScript大师,顾问和老师。

我敦促每个人都读那篇文章,即使你已经做出了决定。

以下是要点:

Function statements have two clear advantages over [const] function expressions: Advantage #1: Clarity of intent When scanning through thousands of lines of code a day, it’s useful to be able to figure out the programmer’s intent as quickly and easily as possible. Advantage #2: Order of declaration == order of execution Ideally, I want to declare my code more or less in the order that I expect it will get executed. This is the showstopper for me: any value declared using the const keyword is inaccessible until execution reaches it. What I’ve just described above forces us to write code that looks upside down. We have to start with the lowest level function and work our way up. My brain doesn’t work that way. I want the context before the details. Most code is written by humans. So it makes sense that most people’s order of understanding roughly follows most code’s order of execution.

在某些特殊情况下,箭头函数无法达到目的:

如果我们正在更改一个外部API的方法,并且需要对象的引用。 如果需要使用函数表达式专有的特殊关键字:arguments, yield, bind等。 欲了解更多信息: 箭头函数表达式限制

例子:

我在Highcharts API中将此函数指定为事件处理程序。 它是由库触发的,因此this关键字应该匹配特定的对象。

export const handleCrosshairHover = function (proceed, e) {
  const axis = this; // axis object
  proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); // method arguments
};

对于箭头函数,这将匹配声明作用域,并且我们将无法访问API obj:

export const handleCrosshairHover = (proceed, e) => {
  const axis = this; // this = undefined
  proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); // compilation error
};