هل كانت مفيدة؟

سؤال

How to disallow altering of object variables in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Use the concept of freeze() from JavaScript to disallow adding new properties to an object, altering of object properties, etc.

Following is the code wherein we are changing the value but the previous value still remains since we cannot alter properties using freeze() −

Example

const canNotChangeTheFieldValueAfterFreeze = {value1 : 10,value2: 20 };
Object.freeze(canNotChangeTheFieldValueAfterFreeze);
canNotChangeTheFieldValueAfterFreeze.value = 100;
console.log("After changing the field value1 from 10 to 100
="+canNotChangeTheFieldValueAfterFreeze.value1);

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo97.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo97.js
After changing the field value1 from 10 to 100 =10
raja
Published on 07-Sep-2020 12:07:57
Advertisements
هل كانت مفيدة؟
لا تنتمي إلى Tutorialspoint
scroll top