gpt4 book ai didi

javascript - 实现常量变量的正确方法是什么?

转载 作者:行者123 更新时间:2023-11-28 08:23:10 25 4
gpt4 key购买 nike

我在 MDN 中找到了以下内容

// THIS WILL CAUSE AN ERROR
function f() {};
const f = 5;

// THIS WILL CAUSE AN ERROR ALSO
function f() {
const g = 5;
var g;

//statements
}

但是没有描述正确的方法。那么我应该如何实现呢?

最佳答案

引自const's MDN Docs ,

The current implementation of const is a Mozilla-specific extension and is not part of ECMAScript 5. It is supported in Firefox & Chrome (V8). As of Safari 5.1.7 and Opera 12.00, if you define a variable with const in these browsers, you can still change its value later. It is not supported in Internet Explorer 6-10, but is included in Internet Explorer 11. The const keyword currently declares the constant in the function scope (like variables declared with var).

Firefox, at least since version 13, throws a TypeError if you redeclare a constant. None of the major browsers produce any notices or errors if you assign another value to a constant. The return value of such an operation is that of the new value assigned, but the reassignment is unsuccessful only in Firefox and Chrome (at least since version 20).

const is going to be defined by ECMAScript 6, but with different semantics. Similar to variables declared with the let statement, constants declared with const will be block-scoped.

const 不是 ECMA Script 5 的一部分,因此可能不需要所有环境和浏览器都支持它。

要获得类似的行为,您可以查看 macek's answer .

关于javascript - 实现常量变量的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22755203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com