×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Paul Zz
Added: Feb 21, 2017 7:52 AM
Modified: Feb 21, 2017 8:36 AM
Views: 2279
  1. /**
  2. * Creates a clone of the input (or <b>this</b>) object. <br>
  3. * To avoid unexpected results, one should not use this function to clone <b>arrays</b>.<br>
  4. * If you want to be able to clone object with <b>null</b> prototype, remove the
  5. * corresponding statement below (see the comments).
  6. * @method clone
  7. * @param {Object} obj
  8. * @returns {Object|Boolean} Returns a new object or false if the input value is not a valid object.
  9. */
  10. clone: function (obj) {
  11.     var donor;
  12.     if (obj) {
  13.         if (typeof obj !== 'object') {
  14.             return false; // not an object
  15.         }
  16.         donor = obj;
  17.     } else {
  18.         donor = this;
  19.     }
  20.     if (!donor.__proto__) { // remove this statement to be able to clone object with __proto__ === null
  21.         return false; // has not prototype
  22.     }
  23.     if (typeof donor.__proto__ !== 'object') {
  24.         return false; // prototype is not an object
  25.     }
  26.     let result = Object.create(donor.__proto__);
  27.     for (let key in donor) {
  28.         if (!donor.hasOwnProperty(key)) {
  29.             continue;
  30.         }
  31.         result[key] = donor[key];
  32.     }
  33.     return result;
  34. }
  35.