How to prevent a property from being removed or modified?

1

I have an object and would like to prevent certain properties from being modified or removed. The code below is for illustrative purposes:

var pessoa = {
  nome: 'Fulano de Tal',
  doc: '999.999.999-99'
};

console.log(pessoa);
pessoa.doc = '111.111.111-11'; // Modifica
console.log(pessoa);
delete pessoa.doc; // Remove
console.log(pessoa);

Can these actions be prevented?

    
asked by anonymous 31.01.2018 / 06:44

2 answers

2

You can use the Object.freeze () , which prevents object properties from being removed or modified (turns the object into read-only - read-only), thus preventing new properties from being added.

Syntax: Object.freeze(pessoa);

In strict mode ( "use strict"; ) will return errors:

var pessoa = {
  nome: 'Fulano de Tal',
  doc: '999.999.999-99'
};

pessoa.doc = '111.111.111-11'; // Modifica
Uncaught TypeError: Cannot assign to read only property

delete pessoa.doc; // Remove
Uncaught TypeError: Cannot delete property

pessoa.idade = '23'; // Adiciona
Uncaught TypeError: Cannot add property idade, object is not extensible
    
31.01.2018 / 10:57
1

Yes, there is a way to create an immutable variable using es5.

const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false
});

object1.property1 = 77;
// throws an error in strict mode

console.log(object1.property1);
// expected output: 42

This is the same example that the documentation itself uses in:

    
31.01.2018 / 08:57