何时在JavaScript中使用const与对象? [英] When to use const with objects in JavaScript?

查看:109
本文介绍了何时在JavaScript中使用const与对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近阅读了关于ES6 const 的关键字,我可以理解它在这样的事情时的重要性:

I recently read about ES6 const keyword and I can understand its importance when having something like this:

(function(){
    const PI = 3.14;
    PI = 3.15; //  Uncaught TypeError: Assignment to constant variable
})();

所以,没有人可以更改我的 PI 变量。

So, nobody can change my PI variable.

我的误解是我不明白在哪种情况下使用 const 对象可以有意义(除了阻止人们做 myObj = newValue; )。

The misunderstanding I have is that I don't understand in which situation the use of const with objects can make sense (other than preventing people to do myObj = newValue;).

(function(){
    const obj = {a:1 ,b: 2, c:3};
    //obj = {x:7 , y:8, z: 9}
    //This is good
    //TypeError: Assignment to constant variable.

    obj.a=7; obj.b=8 ; obj.c=9;
    console.log(obj); //outputs: {a: 7, b: 8, c: 9}
})();

因此,在声明对象时:我应该说什么时候:现在我必须 const 声明我的对象?

So when declaring an object: when should I say: Now I must declare my object with const?

推荐答案

这是一个常见的误解web, CONST 不会创建不可变的变量,而是创建不可变的绑定。

it is a common misconception around the web, CONST doesn't creates immutable variables instead it creates immutable binding.

例如。

 const temp1 = 1;
 temp1  = 2 //error thrown here.

但是

 temp1.temp = 3 // no error here. Valid JS code as per ES6

所以 const 创建对该特定对象的绑定。 const确保变量 temp1 不会有任何其他对象的Binding。

so const creates a binding to that particular object. const assures that variable temp1 won't have any other object's Binding.

现在来到对象。我们可以使用 Object.freeze

Now coming to Object. we can get immutable feature with Object by using Object.freeze

const temp3 = Object.freeze( {a:3,b:4})
temp3.a = 2 // it wont update the value of a, it still have 3
temp3.c = 6 // still valid but wont change the object

这篇关于何时在JavaScript中使用const与对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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