将 Object.defineProperties 与符号一起使用是否有效?

Is it valid to use Object.defineProperties with symbols?

让我们看下面的代码:

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

这有效吗?

使用本机 Object.defineproperties 代码,我们得到 console.log true。

使用 zone.js

的 polyfill

其形式为:

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

我们得到相同的代码 console.log 未定义。

这是因为 Object.keys 函数。我在谷歌上搜索了一下,但没有找到是否允许这样做的任何地方。

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

您可以随时查看规范,在本例中为 § 19.1.2.3 Object.defineProperties(O, Properties)

它使用 OwnPropertyKeys internal method,它确实列出了对象的所有字符串和符号键。

This is because of the Object.keys function

正确。它应该是 Object.getOwnPropertyNames(props).concat(Object.getOwnPropertySymbols(props)) 而不是。您可能想要使用 zone.js 提交错误。然而,我确实想知道为什么在使用 ES6 符号时需要 ES5 Object.defineProperties 函数的 polyfill?