Nuking misleading properties in `Object.getOwnPropertyDescriptor`

Andrea Giammarchi andrea.giammarchi at gmail.com
Sun Mar 10 01:41:20 PST 2013


for safe definition and more, have a look into redefine
https://github.com/WebReflection/redefine#redefinejs

br


On Sat, Mar 9, 2013 at 7:54 PM, Nathan Wall <nathan.wall at live.com> wrote:

> Given that `defineProperty` uses properties on the prototype of the
> descriptor[1] and `getOwnPropertyDescriptor` returns an object which
> inherits from `Object.prototype`, the following use-case is volatile:
>
>     function copy(from, to) {
>         for (let name of Object.getOwnPropertyNames(from))
>             Object.defineProperty(to, name,
>                 Object.getOwnPropertyDescriptor(from, name));
>     }
>
> If a third party script happens to add `get`, `set`, or `value` to
> `Object.prototype` the `copy` function breaks.
>
>     Object.prototype.get = function() { };
>
>     var x = { foo: 1 };
>     var y = { };
>     copy(x, y); // TypeError: property descriptors must not specify a
> value or
>                 // be writable when a getter or setter has been specified
>
> It's misleading that you can't trust `getOwnPropertyDescriptor` to give
> you a descriptor which you can use to define a property with
> `defineProperty`.
>
> A script which doesn't use `defineProperty` could very well define a `get`
> property on `Object.prototype`, unknowingly breaking other scripts which do
> use `defineProperty`. This is a hazard in the language.
>
> I think one of the following would be an appropriate solution:
>
> (1) "Nuke" the special properties (`get`, `set`, and `value` when any of
> them is not defined) on a descriptor returned by `getOwnPropertyDescriptor`
> which shouldn't be inherited through the descriptor's prototype. By "nuke"
> them, I mean specify that they be defined as `undefined`, much like
> `callee` and `caller` in strict mode. (I don't think strict mode is
> required in this case, though, since I highly doubt anyone could be relying
> on this behavior.)
>
> (2) Use the introduction of `Reflect.defineProperty` as an opportunity to
> "fix" this function to only inspect own properties on the property
> descriptor so that the descriptor's prototype doesn't matter. This is
> similar to the addition of `Number.isNaN` to fix the broken `isNaN`.
>
> Nathan
>
>
> [1]
> https://mail.mozilla.org/pipermail/es-discuss/2012-November/026705.html
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130310/aaf00d94/attachment-0001.html>


More information about the es-discuss mailing list