GNOME Bugzilla – Bug 593320
Add Lang.seal() to make an object read-only.
Last modified: 2016-11-29 05:38:42 UTC
Created attachment 141879 [details] [review] Add-Lang.seal-to-make-an-object-read-only.patch The Lang.seal() method is useful for defining scoped constant enumerations, for example: const Color = Lang.seal({ RED: 0, GREEN: 1, BLUE: 2 }) It has other uses, too. The stock spidermonkey shell (but not gjs-console) defines a 'seal' function similar to this.
copyright should be 2009 in lang.c Looks good to me otherwise. If that's really how enums should be done we might want to update the style guide in doc/ (though maybe waiting for others to weigh in first)
I think Lang.seal is useful for making read-only objects irrespective of whatever "the right way" to make enumerations is. Here's another idea for an 'enumeration-creator' helper function: -- enum.js -- const Lang = imports.lang; function enum() { let r = {}; for (let i=0; i<arguments.length; i++) { r[arguments[i]] = i; } return Lang.seal(r); } -- -- Then the color enumeration would be: const Enum = imports.enum.enum; const Color = Enum('RED', 'GREEN', 'BLUE') I don't know which (or either) people would like better -- the first style has the benefit that you can assign custom values to your enumeration; the second might be shorter in the common case -- but I think adding Lang.seal() is the first step for either.
Patch for Lang.seal() pushed. Not updating style guide, since there's been a deafening silence on that topic.
Meant to follow up earlier, not sure if you guys have seen the ECMAScript 5 stuff: http://ejohn.org/blog/ecmascript-5-objects-and-properties/ It'd be nice to move GNOME closer to this, in gjs' case this blocks on Spidermonkey, but we may want to avoid adding things now that will be covered by ES5. In this particular case, it may be possible to add this to Object by default now as a non-enumerable property.
Hm, Lang.seal() (and spidermonkey's seal() ) seems to be equivalent to the future Object.freeze(). The naming conflict is unfortunate: ECMAScript 5's Object.seal() prevents the addition of properties, but does not prevent writes to the existing properties. It seems like it would be straightforward to define Lang.seal(x) as Object.freeze(x) when ECMAScript 5 arrives. Again, the naming confusion is unfortunate -- should we rename the gjs method to Lang.freeze(), confusing present users of spidermonkey's seal() instead of future users of Object.seal()?
Closing, Lang.seal() has since been removed and we do have Object.freeze() available now.