Defining an Object as Constant in Ecma-Script -6

I have the following code for Ecma-Script -6 template constants.

const person = 'John Smith';
console.log(person);

person = 'Naeem Shaikh';    
console.log("{{After changing the value for person.name}}");

console.log(person);

      

Of course it doesn't work. http://www.es6fiddle.net/i3vhumdx/ It gives the following error:

person is read-only

      

now the same as i do with the object.

const person = {name: 'John Smith'};

console.log(JSON.stringify(person));

person.name='Naeem Shaikh';
person.age="24";

console.log("{{After changing the value for person.name}}");

console.log(JSON.stringify(person));

      

http://www.es6fiddle.net/i3vhzblm/

Output:

{"name":"John Smith"}
{{After changing the value for person.name}}
{"name":"Naeem Shaikh","age":"30"}

      

here i can write to read only object without any problem. Can anyone explain this behavior.

+3


source to share


1 answer


You would have the same behavior when changing the argument passed to the function from within this function: if it is a string, the outer one does not change, if it is an object and you change a property, it changes.

The dot is the value of the variable:

  • for an object, this is an object reference, you do not change this reference
  • for a string, it is a string reference that is immutable

When you change properties, you don't change the value (object reference).

Excerpt MDN :



// const also works on objects
const myObject = {"key": "value"};

// However, object attributes are not protected,
// so the following statement is executed without problems
myObject.key = "otherValue";

      

It sounds like you want to have a persistent immutable object. Freeze it:

const person = Object.freeze({name: 'John Smith'});

      

Thus, it would be impossible to change the person's name.

+3


source







All Articles