5

Let's take the following code:

var obj = {};
var x = Symbol();
Object.defineProperties(obj, {
  [x]: {
    value: true,
    writable: true
  },
  "property2": {
    value: "Hello",
    writable: false
  }
  // etc. etc.
});
console.log(obj[x])

Is this valid?

With the native Object.defineproperties code we get in the console.log true.

With the polyfill of zone.js

which is of the form of :

  Object.defineProperties = function (obj, props) {
    Object.keys(props).forEach(function (prop) {
      Object.defineProperty(obj, prop, props[prop]);
    });
    return obj;
  };

we get for the same code of console.log undefined.

This is because of the Object.keys function. I googled around and did not find in any place if this should be allowed or not.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
David Michael Gang
  • 7,107
  • 8
  • 53
  • 98
  • 2
    Syntactically it's valid, practically it is as any other object key is converted to a string, like `Symbol()` (that would be the exact key name in this case). If you really want to be able to key by an arbitrary object - use the ES2015 `Map()` โ€“ zerkms Mar 20 '16 at 08:22
  • Uh, you're not defining a property **on** the symbol here? โ€“ Bergi Mar 20 '16 at 11:54

1 Answers1

2

I googled around and did not find in any place if this should be allowed or not.

You can always check the spec, in this case ยง 19.1.2.3 Object.defineProperties(O, Properties).

It uses the OwnPropertyKeys internal method, which does indeed list all string and symbol keys of an object.

This is because of the Object.keys function

Correct. It should be Object.getOwnPropertyNames(props).concat(Object.getOwnPropertySymbols(props)) instead. You may want to file a bug with zone.js. I do however wonder why you'd need a polyfill for the ES5 Object.defineProperties function when you're working with ES6 symbols?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • But the polyfill shouldn't be applied in an ES6 environment where `Object.defineProperties` is already natively defined? โ€“ Bergi Mar 20 '16 at 12:07