Home > Net >  Object.freeze not working on URL searchParams.set()
Object.freeze not working on URL searchParams.set()

Time:07-17

Is there a way to force an object to be recreated/cloned in order for it to be used specifically on the URL object?

I have tried using Object.freeze(new URL('http://example.com)), however, I can still add and remove searchParams to the object through url.searchParams.set('a', 'b').

I was expecting at least one of these to throw errors:

// Using freeze()
const url = Object.freeze(new URL('http://example.com'))
url.searchParams.set('a', 'b')
console.log(url.toString())

// Using seal()
const url2 = Object.seal(new URL('http://example2.com'))
url2.searchParams.set('c', 'd')
console.log(url2.toString())

// Also freezing the searchParams
const url3 = Object.freeze(new URL('http://example3.com'))
Object.freeze(url3.searchParams)
url3.searchParams.set('e', 'f')
console.log(url3.toString())

I would like to have a way where an error is thrown if the frozen object is used instead of cloned.

CodePudding user response:

There are two potential things tripping you up here:

Firstly, freezing an object doesn't freeze its sub-objects. It is not recursive. There are many implementations of a 'deep freeze' function that does work recursively, MDN's documentation on Object.freeze features one. This may or may not work on built-in types, where some properties are read-only (for example, you cannot execute url.searchParams = <new value>, this raises an error, which will probably break many implementations).

Secondly, setting or altering frozen objects doesn't raise an error unless you're in strict mode. Otherwise, the set just silently fails.

  • Related