论坛首页 Web前端技术论坛

JavaScript中,快速实现一个对象的复制!

浏览 3998 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-03-01  
1、第一种方式,通过JSON转换。
function clone (src) {
    return JSON.parse(JSON.stringify(src));
}


注意,需要引入JSON库:
https://github.com/douglascrockford/JSON-js

2、第二种方式,通过编写JavaScript方法:
function clone(src) {
  function mixin(dest, source, copyFunc) {
    var name, s, i, empty = {};
    for(name in source){
      // the (!(name in empty) || empty[name] !== s) condition avoids copying properties in "source"
      // inherited from Object.prototype.   For example, if dest has a custom toString() method,
      // don't overwrite it with the toString() method that source inherited from Object.prototype
      s = source[name];
      if(!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))){
        dest[name] = copyFunc ? copyFunc(s) : s;
      }
    }
    return dest;
  }

  if(!src || typeof src != "object" || Object.prototype.toString.call(src) === "[object Function]"){
    // null, undefined, any non-object, or function
    return src;  // anything
  }
  if(src.nodeType && "cloneNode" in src){
    // DOM Node
    return src.cloneNode(true); // Node
  }
  if(src instanceof Date){
    // Date
    return new Date(src.getTime());  // Date
  }
  if(src instanceof RegExp){
    // RegExp
    return new RegExp(src);   // RegExp
  }
  var r, i, l;
  if(src instanceof Array){
    // array
    r = [];
    for(i = 0, l = src.length; i < l; ++i){
      if(i in src){
        r.push(clone(src[i]));
      }
    }
    // we don't clone functions for performance reasons
    //    }else if(d.isFunction(src)){
    //      // function
    //      r = function(){ return src.apply(this, arguments); };
  }else{
    // generic objects
    r = src.constructor ? new src.constructor() : {};
  }
  return mixin(r, src, clone);

}
   发表时间:2013-03-03  
楼主无聊吧
0 请登录后投票
   发表时间:2013-03-06   最后修改:2013-03-06
Is jQuery.extend capable of doing this ?
0 请登录后投票
   发表时间:2013-03-07   最后修改:2013-03-07
    var person = new Object();  
    person.name="sjf";  
    person.age=24;  
    person.showName=function(){alert(this.name);}  
    person.showName();//sjf  
    
	//var p2 = person ;
	
	var p2 = new Object();
	for(var p in  person){
	   p2[p]=person[p] ;
	} 
	
    p2.name='jianfeng';  
    p2.showName();//jianfeng  
    person.showName();//sjf  
0 请登录后投票
   发表时间:2013-03-08  
昨天刚刚有了jQuery源码好里面的extend可以做到....
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics