Skip to content

Instantly share code, notes, and snippets.

@ShivrajRath
Last active August 29, 2015 14:23
Show Gist options
  • Save ShivrajRath/4803eda309df043a24f5 to your computer and use it in GitHub Desktop.
Save ShivrajRath/4803eda309df043a24f5 to your computer and use it in GitHub Desktop.
Object Cloning
/**
* Clones an object and retains the prototype chain
* @param {Object} fromObj Object to be cloned
* @returns {Object} Cloned Object
*/
function cloneObj(fromObj) {
var toObj, i;
if (fromObj && typeof fromObj === 'object') {
/** Creates a new instance of fromObj constructor */
toObj = new fromObj.constructor();
for (i in fromObj) {
/** Copies only own property */
if (fromObj.hasOwnProperty(i)) {
toObj[i] = fromObj[i];
}
}
} else {
throw new Error(fromObj + ' cannot be cloned');
}
return toObj;
}
/**Example of using the cloneObj*/
/**
* Profile Class
* @param {String} name Profile's name
* @param {Number} age Profile's age
* @param {Function} toStringFn Overrides the toString function
* @param {Object} father Father's profile
*/
var Profile = function (name, age, toStringFn, father) {
this.name = name || 'NA';
this.age = age;
this.father = father || 'NA';
this.toString = toStringFn;
};
/** Prototype functions */
Profile.prototype = {
setName: function (name) {
this.name = name;
},
setAge: function (age) {
this.age = age;
},
setFather: function (father) {
this.father = father;
},
getName: function () {
return this.name;
},
getAge: function () {
return this.age;
},
getFather: function () {
return this.father;
}
};
/** Resetting the constructor */
Profile.prototype.constructor = Profile;
/**Father's profile*/
var father = new Profile('George H.W. Bush', 92, function () {
return 'Hello there... I\'m ' + this.name;
});
/**Son1's profile*/
var son1 = new Profile('George W. Bush', 62, function () {
return 'Hey folks... You know me... I\'m ' + this.name;
}, father);
/**Son2 is clone of son 1*/
var son2 = cloneObj(son1);
son2.setName('Jeb Bush');
son1.getName(); // Outputs George W. Bush
son2.getName(); // Outputs Jeb Bush
son2.getFather().getName(); //Outputs George H.W. Bush
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment