美文网首页
Object.getOwnPropertyNames vs Ob

Object.getOwnPropertyNames vs Ob

作者: peerben | 来源:发表于2019-04-20 19:22 被阅读0次

简单说就是getOwnPropertyNames会无视enumerate属性,返回所有的ownPropery,
Object.keys会返回可枚举属性(enumerate === true)

There is a little difference. Object.getOwnPropertyNames(a) returns all own properties of the object a. Object.keys(a) returns all enumerable own properties. It means that if you define your object properties without making some of them enumerable: false these two methods will give you the same result.

It's easy to test:

var a = {};
Object.defineProperties(a, {
one: {enumerable: true, value: 'one'},
two: {enumerable: false, value: 'two'},
});
Object.keys(a); // ["one"]
Object.getOwnPropertyNames(a); // ["one", "two"]
If you define a property without providing property attributes descriptor (meaning you don't use Object.defineProperties), for example:

a.test = 21;
then such property becomes an enumerable automatically and both methods produce the same array.

相关文章

网友评论

      本文标题:Object.getOwnPropertyNames vs Ob

      本文链接:https://www.haomeiwen.com/subject/bqglgqtx.html