Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Object.seal() does not throw an exception

I wanted to emulate something like a fixed object, so that no new members can be added to an object. Object.seal(Obj) seemed the right way, but it does not throw an exception when I try to create the new member. The member is not created, but it happens in silence.

var O = { a: 111 }
Object.seal(O)
O.b = 222  <------ here the exception is expected (trying to add a member "b")
O.a = 333
console.log(O) // { a: 333 }

Why would somebody want this silent behavior, why an exception is not thrown?

like image 303
exebook Avatar asked Jul 28 '26 21:07

exebook


1 Answers

The behaviour of an assignment to a sealed object changes with the browsers. The latest release of chrome, for example, behaves as you might expect. For practical purposes, it is safe to assume that adding a member to a sealed object only throws an exception when in strict mode.

;(function () {
    'use strict';
    var O = { a: 111 }
    Object.seal(O)
    O.b = 222
    O.a = 333
    console.log(O) // { a: 333 }
}());

This self-invoking anonymous function throws an error, as you expect. On old browser, unfortunately, you cannot rely on polyfills such as https://github.com/kriskowal/es5-shim

In fact, the seal method on the prototype of Object avoids a 'TypeError' exception, but fails silently when invoked.
From the documentation:

This should be fine unless you are depending on the safety and security provisions of this method, which you cannot possibly obtain in legacy engines.

like image 82
Giovanni Filardo Avatar answered Jul 31 '26 10:07

Giovanni Filardo