Page 171 - Node.js开发指南
P. 171

164  附录 A  JavaScript 的高级特性


                 Object.prototype.clone = function() {
                   var newObj = {};
                   for (var i in this) {
                     newObj[i] = this[i];
                   }
                   return newObj;
                 }

                 var obj = {
                   name: 'byvoid',
                   likes: ['node']
                 };

                 var newObj = obj.clone();
                 obj.likes.push('python');

                 console.log(obj.likes); // 输出 [ 'node', 'python' ]
                 console.log(newObj.likes); // 输出 [ 'node', 'python' ]

                 上面的代码是一个对象浅拷贝(shallow copy)的实现,即只复制基本类型的属性,而
             共享对象类型的属性。浅拷贝的问题是两个对象共享对象类型的属性,例如上例中 likes 属
             性指向的是同一个数组。
                 实现一个完全的复制,或深拷贝(deep copy)并不是一件容易的事,因为除了基本数据
             类型,还有多种不同的对象,对象内部还有复杂的结构,因此需要用递归的方式来实现:


                 Object.prototype.clone = function() {
                   var newObj = {};
                   for (var i in this) {
                     if (typeof(this[i]) == 'object' || typeof(this[i]) == 'function') {
                       newObj[i] = this[i].clone();
                     } else {
                       newObj[i] = this[i];
                     }
                   }
                   return newObj;
                 };

                 Array.prototype.clone = function() {
                   var newArray = [];
                   for (var i = 0; i < this.length; i++) {
                     if (typeof(this[i]) == 'object' || typeof(this[i]) == 'function') {
                       newArray[i] = this[i].clone();
                     } else {
                       newArray[i] = this[i];
                     }
                   }
                   return newArray;
   166   167   168   169   170   171   172   173   174   175   176