I have a module defaultSettingsDefs
which defines and exports an object defaultSettings
:
/* defaultSettingsDefs.js */
const defaultSettings = {
theme: 'light',
}
export { defaultSettings }
And I have a class Settings
(which handles app settings' changes) which is fed defaultSettings
in the constructor like so:
/* index.js */
import { Settings } from './classes/Settings'
import { defaultSettings } from './defs/defaultSettingsDefs'
const settings = new Settings(defaultSettings)
Since defaultSettings
is imported from defaultSettingsDefs
also in many other places within the app, I tried to make it completely immutable in order to avoid accidental overwrites. So in order to take care of the properties I froze the object within the definition itself:
/* defaultSettingsDefs.js */
const defaultSettings = Object.freeze({
theme: 'light',
})
export { defaultSettings }
which works fine and doesn't allow overwriting defaultSettings
's properties neither from index.js
nor, for example, from Settings
itself;
Furthermore, overwriting defaultSettings
itself (not its properties) from index.js
correctly throws an error as expected and desired, since defaultSettings
is a module import:
import { Settings } from './classes/Settings'
import { defaultSettings } from './defs/defaultSettingsDefs'
defaultSettings = 1
// throws "Uncaught TypeError: Cannot set property defaultSettings of #<Object> which has only a getter"
however, defaultSettings
itself can still be overwritten, e.g., from Settings
in the constructor:
/* Settings.js */
constructor(defaultSettings) {
defaultSettings = 1
}
// doesn't throw any error and messes up my app
First off, I don't quite understand why this happens. Shouldn't defaultSettings
's immutability persist when it's passed down to a class?
And secondly, how do I go about fixing this?
Thanks a lot!