2

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?

thatOneGuy
  • 9,977
  • 7
  • 48
  • 90
  • 2
    Possible duplicate of [Can Read-Only Properties be Implemented in Pure JavaScript?](https://stackoverflow.com/questions/366047/can-read-only-properties-be-implemented-in-pure-javascript) – jonrsharpe Sep 19 '18 at 07:20
  • @jonrsharpe I didnt realise a similar question was already asked. I feel the provided answer here seems to solve it better than the one in the link you sent, so perhaps the answer should be passed to that question. – thatOneGuy Sep 19 '18 at 07:23

1 Answers1

6

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';
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320