Exercise - Objects
by jordwms
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
// 2)
//
// Make sure the function ONLY copies "own" properties
// hint: use hasOwnProperty()
var joe = {
name: "Joe",
age: 32
}
function copy(obj) {
var newObj = new Object(),
keys = Object.getOwnPropertyNames(obj);
/* Insert your functionality here */
// loop through the object, property is the 'name'
keys.forEach(function(property) {
Object.defineProperty(
newObj,
property,
Object.getOwnPropertyDescriptor(obj, property)
);
});
return newObj;
}
// 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();
// 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
console.group('#3 Bonus');
joe.copy = function() {
var newObj = new Object(),
keys = Object.getOwnPropertyNames(this),
that = this;
/* Insert your functionality here */
// loop through the object, property is the 'name'
keys.forEach(function(property) {
Object.defineProperty(
newObj,
property,
Object.getOwnPropertyDescriptor(that, property)
);
});
return newObj;
}
console.log( joe.copy() );
console.groupEnd();