如何使 JavaScript 变量完全不可变?

How do I make a JavaScript variable completely immutable?

我听过类似的问题,但不是我想要的答案; 我不算 const 因为: 1). 它实际上并没有使它不可变,它只是使引用不可变 2). 它弄乱了范围,我也希望它在块外工作 3). 并非所有浏览器都支持它

 {
     const hello = ["hello", "world"];
     hello.push("!!!");
     console.log(hello);//outputs "hello", "world", "!!!"
 }
 //and it doesn't, and shouldn't, work here
     console.log(hello);

只需使用Object.freeze

const immutableArray = Object.freeze([1,2,4])

您可以为此使用 Object.freeze(显然只适用于 objects)。

const hello = Object.freeze(["hello", "world"]);

// hello.push("!!!");
// will throw "TypeError: can't define array index property past the end of an array with non-writable length"

// hello.length = 0;
// will fail silently

// hello.reverse();
// will throw "TypeError: 0 is read-only"

// hello[0] = "peter";
// will fail silently

来自 MDN:

The Object.freeze() method freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. In addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in.

但是,如果不对变量值使用 Object.freezeObject.seal,则没有关键字可以定义完全不可变的变量。

对于限制较少的方法 Javascript 也有 Object.seal()

不使用 const 的方法是使用 Object.defineProperty,就像我想要的那样,就范围而言,它的行为类似于 var

{
    Object.defineProperty(typeof global === "object" ? global : window, "PI", {
        value:        Object.seal(3.141593),
        enumerable:   true,
        writable:     false,
        configurable: false
    });
}
console.log(PI); // 3.141593

唯一的问题是它不会在严格模式之外抛出错误。