CodeMoose
CodeMoose

Reputation: 3025

Object.freeze doesnt prevent object from being reinitialized?

Working on some script for an application - I'm not trying to make my client-side code secure, but I am trying to put in enough security that anyone with a console can't walk by and effortlessly overwrite it.

Consider this example:

var config = {};
Object.defineProperty(config, "gridSize", { value : 64, writable : false });
Object.freeze(config);

I'd expect this to create an object config, with a property gridSize set to 64 that can't be overwritten - and then prevent config from being modified with Object.freeze.

Sure enough, when I try to penetrate this script in the console, it holds fast:

> config.gridSize
< 64
> config.gridSize = 32
< 32
> config.gridSize
< 64

But when I attempt to just reset the object directly:

> config = {}
< Object
> config.gridSize = 32
< 32
> config.gridSize
< 32

I thought Object.freeze was supposed to prevent exactly this? Am I doing something wrong, or just misunderstanding its purpose?

Upvotes: 1

Views: 411

Answers (1)

Ry-
Ry-

Reputation: 224942

You’re misunderstanding its purpose. Object.freeze prevents an object completely from being modified, and it’s doing its job. What you’re doing there is making another object. The original object hasn’t changed (well, until it’s destroyed), but it has moved. Variables are just containers, and they invariably vary.

You can use a const, which is not universally supported. (It’s officially part of ECMAScript 6, but not ECMAScript 5.)

If your property actually looks like that, by the way, a simple

const config = Object.freeze({
    gridSize: 64
});

works.

For a “portable” solution, you can define it on the global object (but that’s not pretty):

Object.defineProperty(window, "config", {
    value: Object.freeze({ gridSize: 64 }),
    writable: false,
    configurable: false
});

Upvotes: 2

Related Questions