JS - Object Basics

by Jason Aden

JavaScript

// Working with Objects

// Create a literal
var myObjectLiteral = {
    name: "Mr. Object",
    age: 99,
    toString: function () {
        return this.name;
    }
};

// Access the properties
console.log(myObjectLiteral.name);
console.log(myObjectLiteral["age"]);
console.log(myObjectLiteral.toString());

// Set additional properties
myObjectLiteral.color = "Red faced";
myObjectLiteral[""] = 0; // empty strings will work in []

console.log(myObjectLiteral[""]);

/**
 * Object reflection
 */
console.log(typeof myObjectLiteral);
console.log(typeof myObjectLiteral.color);

console.log("Color property exist: ", "color" in myObjectLiteral);
console.log("valueOf property exist: ", "valueOf" in myObjectLiteral);

console.log(myObjectLiteral.hasOwnProperty("color"));
console.log(myObjectLiteral.hasOwnProperty("valueOf"));

/**
 * Object property descriptors
 */
Object.defineProperty(myObjectLiteral, "newProp", {
    enumerable: true,
    configurable: true,
    value: "This is my value",
    writable: true,
    /*get: function(){
         console.log("I'm a getter!");
        return newProp;
    },
    set: function(value){newProp=value}*/
});
myObjectLiteral.newProp = 5;
console.log(myObjectLiteral.newProp);


/**
 * Object enumeration
 */
function listProperties(o) {
 
    var result = [];
    
    for (var propertyName in o) {
     
        // if (o.hashOwnProperty(propertyName) {
        result.push(propertyName);
        // }
        
    }
    
    return result.join(", ");
    
}

console.log(listProperties(myObjectLiteral));
console.log(Object.keys(myObjectLiteral));
console.log(Object.getOwnPropertyNames(myObjectLiteral));