thatOneGuy
thatOneGuy

Reputation: 10622

Is it possible to create a JavaScript object to not be editable?

For example, say I have his function :

var person = (function(){
    var age = "will"

    function shoutAge(){
        alert(age)
    }

    return {
        shoutAge
    }
})()

After this is created I can do :

person.age = 45;

Granted, this is not the age inside the person scope, but this could cause confusion.

I changed it to use const :

const person = (function(){
    var age = "will"

    function shoutAge(){
        alert(age)
    }

    return {
        shoutAge
    }
})()

But I can still add custom properties.

I misunderstood what const was for, you can't reassign the variable, but you can add properties to it fine.

But is there a way to make it un-editable or is that something that shouldn't be done for some reason?

Upvotes: 2

Views: 781

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370819

One option is to use Object.freeze on the object before returning it, which:

prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed, it also prevents the prototype from being changed.

'use strict';
var person = (function() {
  var age = "will"

  function shoutAge() {
    console.log(age)
  }

  return Object.freeze({
    shoutAge
  })
})();
person.shoutAge();
person.foo = 'foo';

Upvotes: 6

Related Questions