What is the enumerable argument for in Object.create?

泄露秘密 提交于 2019-12-22 05:17:27

问题


In what usages of Object.create do you want to set enumerable to true?


回答1:


A property of an object should be enumerable if you want to be able to have access to it when you iterate through all the objects properties. Example:

var obj = {prop1: 'val1', prop2:'val2'};
for (var prop in obj){
  console.log(prop, obj[prop]);
}

In this type of instantiation, enumerable is always true, this will give you an output of:

prop1 val1
prop2 val2

If you would have used Object.create() like so:

obj = Object.create({}, { prop1: { value: 'val1', enumerable: true}, prop2: { value: 'val2', enumerable: false} });

your for loop would only access the prop1, not the prop2. Using Object.create() the properties are set with enumerable = false by default.



来源:https://stackoverflow.com/questions/9039860/what-is-the-enumerable-argument-for-in-object-create

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!