Freezing object properties or array values, whilst keeping them extensible

Andy Earnshaw andyearnshaw at gmail.com
Tue Jun 4 06:57:14 PDT 2013


Something that occurred to me today is that we have methods for locking
down objects in different ways except for preventing changes to existing
properties.  We have:

 - Object.seal to prevent new properties being added or existing properties
being deleted
 - Object.preventExtensions to prevent new properties being added
 - Object.freeze to prevent new properties being added or existing
properties being altered/deleted

Let's say, though, that my library has a function that accepts an object as
an argument, performs some changes to the values of properties on that
object and returns it to the developer's code for use in a different
function provided by my library.  If I didn't want the developer changing
any of the properties the function sets, I'd have to copy all properties
across to a new object.  That's all well and good, but what if it's an
array?  The length property of an array isn't configurable, so you can't
prevent it being written without freezing it which, in turn, prevents
extensions altogether.

Array.create might have taken care of that, depending on how it was
implemented, but it seems as though that's been deferred in favour of the
<| operator proposal.

If it's not too late for ES6 proposals, I'd like to suggest that we add
either an function to freeze only existing properties of an object, e.g.
Object.lock(), or a function to freeze arrays, e.g. Array.freeze().  The
latter would only freeze the length property and existing array index
properties, keeping it extensible.

Other than introducing another aspect of control over the library user, I
could see this being useful as an optimisation; if the array elements are
locked and you can confirm it was locked by your code then you could make
assumptions about the last element in the array based on an inspection of
the first, eliminating the need for a loop.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130604/f84d7c95/attachment-0001.html>


More information about the es-discuss mailing list