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

Dav*_*ang 6 javascript symbols defineproperty ecmascript-6

我们来看下面的代码:

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

这是有效的吗?

使用本机 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;
  };
Run Code Online (Sandbox Code Playgroud)

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

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

Ber*_*rgi 3

\n

我用谷歌搜索了一下,没有找到任何地方是否应该允许这样做。

\n
\n\n

您始终可以检查规范,在本例中为\xc2\xa7 19.1.2.3 Object.defineProperties(O, Properties)

\n\n

它使用OwnPropertyKeys内部方法,该方法确实列出了对象的所有字符串和符号键。

\n\n
\n

这是因为Object.keys函数

\n
\n\n

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

\n