Advertisement
cortez

JavaScriptClosure

Apr 9th, 2014
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Array.prototype.isArray = true;
  2.  
  3. var ObjectCopier = (function () {
  4.     var self = this; //this variable allow to access the public method inside the private one
  5.  
  6.     function copyArray(arr) { //private function
  7.         var tempArr = [];
  8.         for (var i = 0; i < arr.length; i++) {
  9.             if (typeof (arr[i]) === "object" && arr[i].isArray) {
  10.                 tempArr.push(copyArray(arr[i]));
  11.             } else if (typeof (arr[i]) === "object") {
  12.                 tempArr.push(self.deepCopy(arr[i]))
  13.             } else {
  14.                 tempArr.push(arr[i]);
  15.             }
  16.         }
  17.         return tempArr;
  18.     }
  19.    
  20.     function deepCopy(object) { //public function
  21.         var tempCopy = {};
  22.         if (typeof (object) === "object" && object.isArray) {
  23.             tempCopy= copyArray(object);
  24.         } else if (typeof(object)==="object") {
  25.             for (prop in object) {
  26.                 tempCopy[prop]= this.deepCopy(object[prop]);
  27.             }
  28.         } else {
  29.             tempCopy= object;
  30.         }
  31.         return tempCopy;
  32.     }
  33.  
  34.     //Make the functions public.
  35.     return {
  36.         copyArray: copyArray,
  37.         deepCopy: deepCopy
  38.     }
  39. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement