JS Object Def. Property Get doubt

Hi. With a get method, I limit public access to an obj member so one can only read a property. The code below illustrate the situation:

function Bomb() {
  let id = '345drtsTRS*&gkj';
  this.explode = function(msg) {
    console.log(msg);
  };

  Object.defineProperty(this, 'id', {
    get: function() {
      return id;
    }
  });
};

const b1 = new Bomb();
b1.explode('Bum!');

In the console I do the following test:

b1.id
"345drtsTRS*&gkj"
b1.id = 'new id'
"new id"
b1.id
"345drtsTRS*&gkj"

Indeed it’s read only, but wouldn’t JS supposed to throw an error when I tried:

b1.id = 'new id' ???

=== EOF ===

Only when in strict mode. Then it throws a TypeError.

1 Like