ProfileLEO, A ProgrammerPhotosBlogLists Tools Help

Blog


    August 02

    Script IDE

    Why there is no good IDE for JavaScript? Any one know some and could recommand something?
    these days mess in my brain, not productive.
    July 01

    JavaScript inherit issues

    1.Array or Object member inherit issue,

     An Array or Object member in prototype will be shared by the instances of the class, since it is not deep copied to the instance, just reference, thus change one instance member will affect others.
     function copyObject(srcObj,desObj){
     var memberType="";
     for(var member in srcObj){
      if(typeof srcObj[member]=="object"){
       desObj[member]=(srcObj[member].constructor==Array)?[]:{};
       copyObject(srcObj[member],desObj[member]);
      }else{
       desObj[member]=srcObj[member];
      }
     }
    }
    //class Test
    function Test(){
    }
    //set a array type for Test's prototype
    Test.prototype.tArr=[];
    //Class Test2
    function Test2(){
    }
    //not use system.define method, but copy all Test.prototype to Test2's in deep
    copyObject(Test.prototype,Test2.prototype);

    function testT(){
     var t1=new Test();
     //change t1's tArr[0]
     t1.tArr[0]="orginal";
     //will not affect Test2's new instance it should alert undefined
     var t2=new Test2();
     alert(t2.tArr[0]);
     
     //problem comes, t3 is also a new Test without set tArr but now the tArr[0] have value
     //that setted by t1.
     var t3=new Test();
     alert(t3.tArr[0]);
    }
    2. IE6 and Firefox's diffrent in handling prototype:
    codes here first:
    function Test1(){
    }
    Test1.prototype.t="hello";
    Test1.prototype.f=function(){
     alert("hello! world");
    }
    function copyObject(srcObj,desObj){
     var memberType="";
     for(var member in srcObj){
      if(typeof srcObj[member]=="object"){
       desObj[member]=(srcObj[member].constructor==Array)?[]:{};
       copyObject(srcObj[member],desObj[member]);
      }else{
       desObj[member]=srcObj[member];
      }
     }
    }
    function Test2(){
    }
    copyObject(Test1.prototype,Test2.prototype);
    for(var mem in Test2){
     alert(mem);
    }
    If you tried to loop Test2 Class  before copy a prototype to it, IE and Firefox will not alert a "prototype" both. at this point, they are same, but after Test2 get a prototype, like codes above, Firefox will alert a member name "prototype" but IE will not. So if you want to copy prototype from one class to another in IE, you should do like this "copyObject(Test1.prototype,Test2.prototype);
    " but not "copyObject(Test1,Test2);", as you can imagine, firefox will allow you to do it with second aproach.