I am having some Problems with JavaScript. I have got the following code:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function Control(){
var name;
this.setName = function(newName){
name = newName;
};
this.getName = function(){
return name;
};
}
function SpecializedControl(){
}
SpecializedControl.prototype = new Control();
function Form(){
var formControls = [];
this.addControl = function(control){
formControls.push(control);
alert(formControls[0].getName());
};
}
var form = new Form();
var control1 = new SpecializedControl();
control1.setName("Control1");
form.addControl(control1);
var control2 = new SpecializedControl();
control2.setName("Control2");
form.addControl(control2);
</script>
</head>
<body>
</body>
</html>
The SpecializedControl inherits from the Control class.
The addControl function in the Form class just adds the control to an array.
The problem is that when I add more than one SpecializedControl, the values in the array are kind of overriden, that means that when I access the first item in the array, which should be "Control1" I get "Control2". Control1 is not in the array any longer.
When I use the same function with Control objects as parameters everything works as expected.
Does someone know why this happens and what can be done to correct this?