is it possible to seal JS objects automatically?

Viewed 249

I want to seal JavaScript objects as soon as they get created:

'use strict';

class Test {
}

const t = Object.seal(new Test());
t.p = true; // error!

Is there a way to do it automatically, something like below?

Test.sealInstances = true // I wish sealInstances was real!
const t = new Test();
t.p = true; // error

I know I could do this:

function createTest() {
  return Object.seal(new Test())
}

and use createTest everywhere but I'd like the new Test() syntax more.

1 Answers

Just put Object.seal in the constructor:

'use strict';

class Test {
  constructor() {
    Object.seal(this);
  }
}

const t1 = new Test();
const t2 = new Test();
try {
  t1.p = 'p';
} catch(e) { console.log(e.message) }
try {
  t2.z = 'z';
} catch(e) { console.log(e.message) }

Related