Note that there are some explanatory texts on larger screens.

plurals
  1. POJavaScript Array Initialisation in Simple JavaScript Inheritance
    text
    copied!<p>I'm currently working on some code based on John Resig -<a href="http://ejohn.org/blog/simple-javascript-inheritance/" rel="nofollow noreferrer">Simple JavaScript Inheritance</a>. 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:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; /* 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+"&lt;br/&gt;"); a.arrayModif(); document.write("This is a after modifications:"+a.arrayTest+"&lt;br/&gt;"); var b=new Person(); document.write("This is b after creation:"+b.arrayTest+"&lt;br/&gt;"); }; &lt;/script&gt; &lt;/head&gt; &lt;body onload="example();"&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And it will have the following output:</p> <pre><code>This is a before any modifications: This is a after modifications:4,2 This is b after creation:4,2 </code></pre> <p>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():</p> <pre><code>This is a before any modifications: This is a after modifications:4,2 This is b after creation: </code></pre> <p>Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload