Exercise - Objects

by Diarmuid Dunne

JavaScript

// 1)
//
// Create a function that accepts an object as an argument
// and returns a copy of that object
// So that the following example will run correctly
var joe = {
    name: "Joe",
    age: 32
}
function copy(obj) {
    
    /* Insert your functionality here */
    name : obj.name;
    age : obj.age;
}
console.log(copy);

// Testing your copy function...
var jim = copy(joe);
console.group("Test");
if (jim === joe) {
    console.log("Nope! They are the same object")   
} else {
     console.log("Great job! You made a copy.");   
}
console.log("The two objects are:", jim, ",", joe);
console.groupEnd();

// 2)
//
// Make sure the function ONLY copies "own" properties
// hint: use hasOwnProperty()
//getOwnPropertyNames
//loop through for each prop name create new and lookup value on old object

//var joeProps = Object.getOwnPropertyNames(joe);
//console.log(joeProps);

//for(var i = 0; var < joeProps.length; i ++)
//{
//    joeProps[i] : joe.joeProps[i];
//}

function copy(obj){
    var newObj = {};
    
    Object.getOwnPropertyNames(obj).forEach(function(prop){
        newObj[prop] = obj[prop];
    });
    
    return newObj;
}

// 3) Bonus
//
// Add the function as a method on the joe object, 
// then invoke the method of that object to copy it
// hint: you will use "this" keyword in your method
//
// ex: joe.copy(); // outputs a copy