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.
I use a small addition that checks for arrays in the class (not in sub-objects of that class!), and copies those arrays on initialization to get a local copy instead of one in the prototype only.