Javascript - (Object) Property

About

Property Management of an object

A property has :

Management

Exist

var myObj = {myProp:3} ;
if ("myProp" in myObj) {
    console.log("Yes, i have that property");
} 
if (!("myFakeProp" in myObj)) {
    console.log("No, i haven't that property");
}

Computed property names (ES2015)

Property names can be dynamic

var param = 'size';
var config = {
  [param]: 12,
  ['mobile' + param.charAt(0).toUpperCase() + param.slice(1)]: 4
};

console.log(config); // {size: 12, mobileSize: 4}

Delete property

Reference/Operators/delete

delete object.property
delete object['property']

Dynamic Object Property access

var obj = { 
     a: "hello world", 
     b: 42 
}; 

var b = "a"; 

console.log(obj[ b]); // "hello world" 
console.log(obj["b"]); // 42

Object or prototype Property

A property may be owned by its prototype.

// An object
var person = {
   name: "Nicolas", 
   length: 180
};

// A constructor
function ColoredPerson() {
    // Rode piet !
    this.color = "red";
}

// Set the prototype to be the person object (dynamic inheritance)
// All new ColoredPerson must inherit its properties.
ColoredPerson.prototype = person;

// Create a new object
var coloredPerson = new ColoredPerson();

// Loop through the properties
var propSource;
for (var prop in coloredPerson) {
    if (coloredPerson.hasOwnProperty(prop)) {
        propSource = "object";
    } else {
        propSource = "prototype";
    }
    console.log("The property " + prop + " (value:" + coloredPerson[prop] + ") is a property from the " + propSource);
}

Loop (for property in object)

Reference/Statements/for...in.

The loop iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).

var person = {name: "Nicolas", length: 180};

function ColoredPerson() {
    // Rode piet !
    this.color = "red";
}
ColoredPerson.prototype = person;

var coloredPerson = new ColoredPerson();

var propSource;
for (var prop in coloredPerson) {
    if (coloredPerson.hasOwnProperty(prop)) {
        propSource = "object";
    } else {
        propSource = "prototype";
    }
    console.log("The property " + prop + " (value:" + coloredPerson[prop] + ") is a property from the " + propSource + ".");
}

Length

console.log("The number of key/properties in the global object is "+ Object.keys(this).length);

Audit

to audit if a static property value was accessed such as the userAgent, you can define a getter

Example: if a script the userAgent property, the property window.navigator.sniffed is set to true

window.navigator.__defineGetter__('userAgent', function() {
    window.navigator.sniffed = true;
    return userAgent;
});

Powered by ComboStrap