Featured post

Closures, Lexical Scoping And Scope chain In JavaScript

Closures...You have heard a lot, or might have tried to study from different sources, but failed to get the point. Well to under...

Tuesday 1 March 2016

JavaScript Properties


In this post, we will talk about JavaScript properties, what is inheritance and enumerability.
There are 3 attributes of object's property: writable, enumerable and configurable. Earlier in this post we have seen how object can be created and initialized at the same time like this:

var child = Object.create({a: "Parent Property"}, {
      foo: { writable: true, configurable: true, value: "Everything is weird." }
})

Here, foo is property of child object and it has writable and configurable attribute set. If writable is true, that property can be altered later else not. If configurable is true, that property can be deleted using delete operator else not. And finally if enumerable is true, property will be iterated using for..in loop in it's child objects.

Accessing Properties


Properties can be accessed through its own definition or from its prototype chain.If you are accessing a property from any object than first, object's definition will be searched, if property is not available over there then object's immediate prototype is searched, if not even available there too then prototype's prototype is searched. The search goes on until property is found or up to the highest prototype from prototype chain. But there are some methods defined if you want to iterate only object's own property or all the properties from prototype chain or enumerable properties etc.

Iterating all own properties


var obj = {
      a: "Property of obj"
}
Object.getOwnPropertyNames(obj);
obj.hasOwnProperty(a);
Object.getOwnPropertyDescriptor(obj, a);
obj.b = "Another Property";
obj[c] = "One more Property";
delete obj.c;
delete obj[b];
Object.defineProperty(obj, "foo", { enumerable: true, writable: true, configurable: false, value: "Awesome!" });

Above methods will be used for iterating/accessing all the properties defined by object itself and not inherited from its prototype.

Iterating own enumerable properties


Object.keys(obj);

Above method will be used for iterating all the enumerable properties defined in object defination itself.

Enumerable Inherited Properties


for(var key in obj) {
      console.log(key);
}

All object's properties and enumerable inherited properties.

All Inherited Properties


propName in obj;
obj.propName;
obj[propName];
Using above method, all properties can be accessed.

This was very small post which covered very simple topic. I hope you like it. Please drop your comments.

No comments: