Javascript - (Object) Property

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard > Javascript - Object

1 - About

Property Management of an object

Advertising

3 - Management

3.1 - 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");
}

3.2 - 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}

3.3 - Delete property

Reference/Operators/delete

delete object.property
delete object['property']

3.4 - 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

3.5 - 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);
}

Advertising

3.6 - 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 + ".");
}

3.7 - Length

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

web/javascript/es/object/property.txt · Last modified: 2019/02/16 17:40 by gerardnico