ryanve
ryanve

Reputation: 52591

What is the enumerable argument for in Object.create?

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

Upvotes: 7

Views: 2422

Answers (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.

Upvotes: 13

Related Questions