Tip of the day - Javascript

Un trucchetto al giorno toglie le complicazioni di torno!

Guarda tutti i nostri piccoli consigli per mantenerti allenato o conoscere qualcosa di nuovo sul magico mondo JS.

Vedi gli altri tips

Different methods to manage the immutability of the objects

2021-07-23 - JavaScript

1// JS Tip of the Day
2// Different methods to manage the immutability of the objects
3
4// Object.preventExtensions
5const heroPreventExt = { name: 'Batman', weapon: 'Batarang' };
6Object.preventExtensions(heroPreventExt);
7heroPreventExt.weapon = 'Grapple Gun'; // Allowed!
8Object.defineProperty( heroPreventExt, 'weapon', { 
9    writable: false,
10});
11delete heroPreventExt.weapon; // Allowed!
12heroPreventExt.vehicle = 'Batmobile'; // Not Allowed!
13console.log(heroPreventExt.vehicle); 
14/* undefined 
15   or in Strict Mode
16   TypeError: Cannot add property vehicle, object is not extensible
17*/ 
18Object.isExtensible(heroPreventExt) //false
19
20
21// Object.seal
22const heroSeal = { name: 'Batman', weapon: 'Batarang' };
23Object.seal(heroSeal);
24heroSeal.weapon = 'Grapple Gun'; // Allowed!
25Object.defineProperty( heroSeal, 'weapon', { 
26    writable: false,
27}); // Not Allowed!
28delete heroSeal.weapon; // Not Allowed!
29/* false 
30   or in Strict Mode
31   TypeError: Cannot delete property 'weapon' of #<Object>
32*/
33heroSeal.vehicle = 'Batmobile'; // Not Allowed!
34console.log(heroSeal.vehicle); 
35/* undefined 
36   or in Strict Mode
37   TypeError: Cannot add property vehicle, object is not extensible
38*/ 
39Object.isSealed(heroSeal) // true
40
41
42// Object.freeze
43const heroFreeze = { name: 'Batman', weapon: 'Batarang' };
44Object.freeze(heroFreeze);
45heroFreeze.weapon = 'Grapple Gun'; // Allowed!
46/* 
47  In Strict Mode
48  TypeError: Cannot assign to read only property 'weapon' of object '#<Object>'
49*/
50Object.defineProperty( heroFreeze, 'weapon', { 
51    writable: false,
52}); // Not Allowed!
53delete heroFreeze.weapon;
54/* undefined 
55   or in Strict Mode
56   TypeError: Cannot add property vehicle, object is not extensible
57*/ 
58heroFreeze.vehicle = 'Batmobile'; // Not Allowed!
59console.log(heroFreeze.vehicle); 
60/* undefined 
61   or in Strict Mode
62   TypeError: Cannot add property vehicle, object is not extensible
63*/ 
64Object.isFrozen(heroFreeze) // true
#JStipoftheday