JavaScript: Property, Prototype Chain, Enumerable: Accessing & Listing Properties

, , …,
Buy Xah JavaScript Tutorial.

This page gives a summary of operations on object properties. Some will travese the prototype chain, some not, some depend on whether the property's enumerable attribute is true. 〔➤ JavaScript: Property Attributes: Writable, Enumerable, Configurable

First, remember that in JavaScript, each object has a parent (called its prototype), and parent also has parent, forming a prototype chain. When looking up a property, JavaScript'll check the object's property, if not found, then check its parent, up the prototype chain, until found or root object is reached. 〔➤ JavaScript: Understanding Prototype & Inheritance

Property Operations: Access, Set, Delete, Check Existence

Here's a summary of operations on property.

JavaScript property operations
syntaxmeaningproto chain
o["p"]Return the value of the property.yes
o["p"] = valueModify or create a new property for the
delete o["p"]Delete a property p in o if it
o.hasOwnProperty("p")true if the object has the
p in otrue if is own property or in prototype chain.yes

〔➤ JavaScript: Dot Notation vs Bracket Notation for Accessing Properties〕 〔➤ JavaScript: Understanding Prototype & Inheritance

Listing & Enumerating Properties

Here's a summary of ways to list or loop thru properties.

JavaScript property listing operations
syntaxmeaningproto chainenumerable only
Object.getOwnPropertyNames(o)Return a array of all own property names. (including non-enumerable ones)nono
Object.keys(o)Return a array of property names that are o's own properties, and their “enumerable” attributes are true.noyes
for (var x in o) {…}loop thru all enumerable properties that is o's own properties or is in the prototype chain of o, set the property name to x. Order is not guaranteed.yesyes

list all enumerable properties, of a object and its prototype chain:

var pName , pValue;

var o1 = {"a":3};

var o2 = Object.create(o1); // o2's parent is o1
o2.p = 4;

// list all enumerable properties, of a object and its prototype chain
for (var x in o2) {
    pName = x;
    pValue = o2[x];
    console.log( pName);
    console.log( pValue);

// output
// p
// 4
// a
// 3

〔➤ JavaScript Array Methods

blog comments powered by Disqus