Skip to content

Instantly share code, notes, and snippets.

@mauriciosoares
Created June 10, 2014 14:18
Show Gist options
  • Save mauriciosoares/af1c3d3dc301babb68e6 to your computer and use it in GitHub Desktop.
Save mauriciosoares/af1c3d3dc301babb68e6 to your computer and use it in GitHub Desktop.
// with this extend method, the second object is created, but there is no object reference between them.
var extend = function(parent, child) {
var i = 0,
child = child || {},
toStr = Object.prototype.toString,
arrayRef = '[object Array]';
for(i in parent) {
if(parent.hasOwnProperty(i)) {
if(typeof parent[i] === 'object') {
child[i] = (toStr.call(parent[i]) === arrayRef) ? [] : {};
extend(parent[i], child[i]);
} else {
child[i] = parent[i];
}
}
}
return child;
}
var father = {
name: 'Adam',
age: 37,
someArray: [1,2,3],
someObjetc: {
one: 1,
two: 2
}
}
var child = extend(father);
child.someArray === father.someArray; // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment