// 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) {
/* Insert your functionality here */
var propNames = Object.getOwnPropertyNames(obj);
var copy = Object.create(Object.getPrototypeOf(obj));
propNames.forEach(function(name) {
var descrip = Object.getOwnPropertyDescriptor(obj, name);
Object.defineProperty(copy, name, descrip);
});
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()
// 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
Object.defineProperty(joe, 'copy', {
enumerable : true,
value: function() {
/* Insert your functionality here */
// Save reference to the original object
var original = this;
var propNames = Object.getOwnPropertyNames(original);
var copy = Object.create(Object.getPrototypeOf(original));
propNames.forEach(function(name) {
var descrip = Object.getOwnPropertyDescriptor(original, name);
Object.defineProperty(copy, name, descrip);
});
return copy;
}
});
// Testing your copy function...
var jim = joe.copy();
console.group("Test 2");
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, ",",...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.