Exercise - JS Objects - Mutability

by Jennifer Piccione

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 newObject = {};
    
    for (var propertyName in obj) {
        if (obj.hasOwnProperty(propertyName)) {
            newObject[propertyName] = obj[propertyName];
        }
    }
    return newObject;
}

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

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

// 4) Ultra bonus
//
// Make it so that ALL objects inherit this "copy" method
// hint: you will extend Object.prototype