views:

79

answers:

2

I'm currently working on some code based on John Resig -Simple JavaScript Inheritance. And i'm having some trouble with the initialization of arrays. If i put an array as an attribute for an object and don't initialize the array during the call of init(), all the modification made to the array like push, unshift will affect further creations of objects. As i dunno if i'm clear enough, here is an example:

<html>
  <head>
    <script type="text/javascript">
    /*
    insert all the John Resig code here
     */

    var Person = Class.extend({
      arrayTest:[],

      init: function(){
      },
      arrayModif: function(){
        this.arrayTest.push(4);
 this.arrayTest.push(2);
      }
    });

    function example(){
      var a=new Person();
      document.write("This is a before any modifications:"+a.arrayTest+"<br/>");
      a.arrayModif();
      document.write("This is a after modifications:"+a.arrayTest+"<br/>");
      var b=new Person();
      document.write("This is b after creation:"+b.arrayTest+"<br/>");
    };
   </script>
  </head>
  <body onload="example();">
  </body>
 </html>

And it will have the following output:

This is a before any modifications:
This is a after modifications:4,2
This is b after creation:4,2

I was wondering if someone had any idea of how to modify John Resig code to achieve the following output, without putting something in init():

This is a before any modifications:
This is a after modifications:4,2
This is b after creation:

Thanks.

A: 

I haven't used John Resig's code yet but I'd try to set the initial value of variables in the constructor:

var Person = Class.extend({ 
  arrayTest:[], 

  init: function(){ 
      arrayTest = [];
  }, 
x4u
`this.arrayTest = []`. It's not needed at all on the prototype.
Crescent Fresh
+2  A: 

Combining what x4u and Crescent Fresh said, it looks like you want:

var Person = Class.extend({ 

   init: function(){ 
      this.arrayTest = [];
   },
   arrayModif: function(){
      this.arrayTest.push(4);
      this.arrayTest.push(2);
  }
});
BobS
Yes, that was what I actually meant. ;)
x4u
Yeah but i wrote: without putting something in init().I knew that putting the this.arrayTest=[] in the initialization works, i was just wondering if somehow, it could be achieved without adding something to the init(), and only changing something in John Resig code.
Py