Object Examples

by Joshua McNeese

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: 0,
    writable: true
});
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));

/**
 * Get/Set
 */
function Archiver() {

    var archive = [];
    var temperature = 0;

    Object.defineProperty(this, 'temperature', {
        get: function () {
            return temperature;
        },
        set: function (value) {
            temperature = value;
            archive.push(value);
        }
    });

    this.getArchive = function () {
        return archive;
    };

}

var arc = new Archiver();
console.log(arc.temperature);
arc.temperature = 11;
arc.temperature =...