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
[email protected]
https://mail.mozilla.org/listinfo/es-discuss