Exercise - JS Objects - Mutability
by cmckeachie
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) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return 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()