Exercise - JS Objects - Mutability
by Ryan Morris
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 w/out spitting out "Nope"
var joe = {
name: "Joe",
age: 32
}
function copy(obj) {
var objectCopy = {};
for (var propName in obj) {
objectCopy[propName] = obj[propName];
}
return objectCopy;
}
var jim = copy(joe);
if (jim === joe) {
console.log("Nope! They are the same object")
}
console.log("check your copying:", jim, joe);
// 2)
//
// Make sure the function ONLY copies "own" properties
// hint: use hasOwnProperty()
function copy(obj) {
var objectCopy = {};
for (var propName in obj) {
if (obj.hasOwnProperty(propName)) {
objectCopy[propName] = obj[propName];
}
}
return objectCopy;
}
// 3) Bonus
//
// Add the function as a method on an object,
// then invoke the method of that object to copy it
// hint: you will use "this" keyword in your method
//
// ex: myObject.copy(); // outputs a copy
var myObject = {
name: "Ryan",
age: 33
};
myObject.copy = function copy() {
var objectCopy = {};
for (var propName in this) {
if (this.hasOwnProperty(propName)) {
objectCopy[propName] = this[propName];
}
}
return objectCopy;
}
var newObject = myObject.copy();
console.log(newObject);
console.log(newObject !== myObject);
// 4) Ultra bonus
//
// Make it so that ALL objects inherit this "copy" method
// hint: you will extend Object.prototype
Object.prototype.copy = myObject.copy;
var newjoe = joe.copy();
console.log(newjoe, newjoe !== joe);