简体   繁体   中英

What's the proper way to implement constant variable?

I found the following in the 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
}

But there is no description of proper way to do. So how should I implement?

ECMAScript 5 doesn't really support this. There's a couple tricks you could use though.

You could try something like this

var f = (function() {

  var g = 5;

  return function() {
    return g;
  };

})();

Now, every time you run f() , you will also get 5 , and it's impossible to change the value of g


Another thing you could do is use Object.defineProperty

var f = {};

Object.defineProperty(f, "g", {
  configurable: false,
  value: 5
});

f.g; // 5

Even if you try to change the property, fg will stay set to 5

f.g = 10;
f.g; // 5

If you're working with CommonJS style modules, you sort of get this functionality for "free". Again, g is non-configurable and always guaranteed to be 5.

a.js

var g = 5;

function foo() {
  return g;
}

module.exports = foo;

b.js

var a = require("./a");

a(); // 5

Quoting from the 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 is not part of ECMA Script 5, so it may not have to supported by all the environments and browsers.

To have the similar behavior, you can see macek's answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM