What is the preferred declaration convention for o

2020-03-06 03:44发布

问题:

I'm not asking what's technically possible; I know you can do

const a = [];
const b = {};
a.push['sup'];
b.test = 'earth';

What I'm wondering is whether there's any convention for preferring let over const when it comes to arrays and objects that will have their internals modified. If you see an object declared with const, do you assume the intention was for the object to be immutable, and would you have preferred to see let instead, or, since some linters (like tslint) have a problem with that, is it better just to declare it with const and trust that anyone else reading the code knows that that doesn't mean it's immutable?

回答1:

The const keyword in front of an object implies that there is an object, and you're working with references to alter it. It also (correctly) implies that you should not attempt to reassign references to this object.

const obj = {a: 'foo', b: 'bar'};

const obj2 = {z: 'baz'};

obj = obj2; // const will prevent this operation. 

const does not imply that the object properties should not be altered. It does imply that you should not try to change the reference.

If you plan to reassign references to the object, then you use let.

Source: AirBnB Javascript Style Guide