将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.
With the native Object.defineproperties code we get in the console.log true.
使用zone.js的polyfill
With the polyfill of zone.js
其形式为:
Object.defineProperties = function (obj, props) {
Object.keys(props).forEach(function (prop) {
Object.defineProperty(obj, prop, props[prop]);
});
return obj;
};
对于未定义的console.log,我们得到相同的代码.
we get for the same code of console.log undefined.
这是因为存在Object.keys函数.我四处搜寻,在任何地方都找不到是否应该允许这样做.
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.
推荐答案
我四处搜寻,没有发现是否应允许这样做.
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).
You can always check the spec, in this case § 19.1.2.3 Object.defineProperties(O, Properties).
它使用 OwnPropertyKeys
内部方法,该方法的确列出了对象的所有字符串和符号键.
It uses the OwnPropertyKeys
internal method, which does indeed list all string and symbol keys of an object.
这是由于
Object.keys
功能
正确.它应该是Object.getOwnPropertyNames(props).concat(Object.getOwnPropertySymbols(props))
.您可能要使用zone.js提交错误.但是,我确实想知道为什么在使用ES6符号时为什么需要对ES5 Object.defineProperties
函数使用polyfill?
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?
这篇关于将Object.defineProperties与符号一起使用是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!