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?
The values in the array aren’t being overridden; the problem is both controls share the same
namevariable. Because theControlfunction only executes once, there is only onenamevariable ever declared.You have two main options to fix this. (1) Make
namean instance variable which is specific to each individual control (e.g.this._name). (2) Execute theControlfunction from inside theSpecializedControlconstructor. (Actually, IMO, for a well-balanced and thorough inheritence model you should be doing a bit of both of these methods).Here are three working solutions. The first two use options (1) and (2) respectively. The third combines both methods and is the way I would do it (but requires joi).
Option 1:
Option 2:
Option 3: