How to prevent a property from being removed or modified?

Asked

Viewed 40 times

1

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

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);

It is possible to prevent these actions ?

2 answers

2


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

Syntax: Object.freeze(pessoa);

In strictly speaking ("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

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.