代码之家  ›  专栏  ›  技术社区  ›  Ben

javascript克隆代码和属性

  •  0
  • Ben  · 技术社区  · 14 年前

    有没有一种快速的方法来“超级”深度克隆一个节点,包括它的属性?(我想还有方法)

    var theSource = document.getElementById("someDiv")
    theSource.dictator = "stalin";
    
    var theClone = theSource.cloneNode(true);
    
    alert(theClone.dictator); 
    

    新克隆的对象没有 dictator 财产。现在,假设我有一千处房产 theSource

    //编辑

    @法布里齐奥

    你的 hasOwnProperty

    temp = obj.cloneNode(true);
    
    for(p in obj) {
      if(obj.hasOwnProperty(p)) { eval("temp."+p+"=obj."+p); }
    }
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   fcalderan fcalderan    14 年前

    保存许多属性的最好方法可能是创建一个属性对象,在该对象中可以存储所有属性,例如。

    thesource.myproperties = {}
    thesource.myproperties.dictator1 = "stalin"; 
    thesource.myproperties.dictator2 = "ceasescu"; 
    thesource.myproperties.dictator3 = "Berlusconi";
    ...
    

    那你只能复制一个属性

    theclone.myproperties = thesource.myproperties
    

    for 为已存储的所有属性循环

    for (p in thesource) {
      if (thesource.hasOwnProperty(p)) {
        theclone.p = thesource.p;
      }
    }
    
    推荐文章