Exercise - Objects

by manu troiani

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) {
    
    var propertyNames = Object.getOwnPropertyNames(obj); // ["name", "age"]
    var len =  propertyNames.length;
    alert('list of names: '+ propertyNames);
	//var props = Object.getOwnPropertyDescriptor(obj);
	//alert(props);
    var myclone = new Object();
    for ( var i=0; i <len ; i++){
        //var currentvalueForGiveObj = obj[propertyNames[i]];
        //alert ('currentValue for item ' + i + ' should be: ' + propertyNames[i] + "= "+ 	currentvalueForGiveObj);
        //myclone[propertyNames[i]] = myclone[currentvalueForGiveObj];
        var s = obj[propertyNames[i]];
       	myclone[propertyNames[i]] = myclone[obj[propertyNames[i]]];
        
	}
    
    console.log(myclone.toString());
    return myclone; 

}

// 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()

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