让我们看下面的代码:
var obj = {};
var x = Symbol();
Object.defineProperties(obj, {
[x]: {
value: true,
writable: true
},
"property2": {
value: "Hello",
writable: false
}
// etc. etc.
});
console.log(obj[x])
这有效吗?
使用 native 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?
关于javascript - 将 Object.defineProperties 与符号一起使用是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36111582/