Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the enumerable argument for in Object.create?

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

like image 421
ryanve Avatar asked Jan 27 '12 20:01

ryanve


People also ask

What is enumerable property in object?

Enumerable properties are those properties whose internal enumerable flag is set to true, which is the default for properties created via simple assignment or via a property initializer. Properties defined via Object. defineProperty and such are not enumerable by default.

What does object create do in JS?

The Object. create() method creates a new object, using an existing object as the prototype of the newly created object.

Are objects enumerable in JavaScript?

An object property has several internal attributes including value , writable , enumerable and configurable . See the Object properties for more details. The enumerable attribute determines whether or not a property is accessible when the object's properties are enumerated using the for...in loop or Object.

What's an enumerable?

Definitions of enumerable. adjective. that can be counted. synonyms: countable, denumerable, numerable calculable. capable of being calculated or estimated.


1 Answers

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.

like image 160
André Alçada Padez Avatar answered Oct 31 '22 19:10

André Alçada Padez