Exercise - JS Objects - Mutability

by iboulder

HTML

<h1>
  Class Exercise to copy class
</h1>

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
//
// Hint: you'll use a for..in loop
var joe = {
  name: "joe",
  age: 32,
  hasAjob: 'You Wish'
}

var jim = {}

function copy(obj) {
 
  //var jim = {};

  /* Insert your functionality here */
  var myEnum = Object.getOwnPropertyNames(obj)
  console.log('myEnum is: ' + myEnum)
  for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      console.log('prop: ' + prop)
      console.log(' val: ' + obj[prop]);
      console.log('obj.prop: ' + obj[prop])
      jim[prop] = obj[prop];
    }
    obj[prop]; // true
  } 
 return jim
}

// 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: ", jim, ", joe: ", joe);
console.groupEnd();

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