I'm trying to create a grid using javascript prototype inheritance, however there is a problem I could not understand. In some point of the code the "new" keyword seems not work.
It's hard to explain, so the code are below and I put comments in the main points.
<head>
<!-- this is the "parent class" -->
<script type='text/javascript'>
// constructor
function Container(CSSClassName) {
this.CSSClassName = CSSClassName;
this.build = ContainerBuild;
this.components = new Object();
this.addComponent = ContainerAddComponent;
this.getComponent = ContainerGetComponent;
}
/*
* methods
*/
function ContainerAddComponent(id, component) {
this.components[id] = component;
}
function ContainerGetComponent(id) {
return this.components[id];
}
function ContainerBuild() {
this.element = document.createElement('div');
this.element.className = this.CSSClassName;
for (var i in this.components) {
this.element.appendChild(this.getComponent(i).build());
}
return this.element;
}
</script>
<!-- Below I'm using prototype inheritance -->
<script type='text/javascript'>
Grid.prototype = new Container('grd');
function Grid() {
this.addComponent('body', new GridPart());
this.addComponent('foot', new GridPart());
}
GridPart.prototype = new Container('grd-part');
function GridPart() {
this.addComponent('comp', new Container('comp')); // this new keywork seems not to work.
/* ***** I tried this code, but the result was the same.
var comp = new Container('comp');
this.addComponent('comp', Object.create(comp)); // same unexpected result.
*/
}
window.onload = function() {
var grd = new Grid();
document.getElementById('grd').appendChild(grd.build());
grd.getComponent('body').element.style.background = 'red'; // ok!
grd.getComponent('body').getComponent('comp').element.style.background = 'gold'; // unexpected behavior
// Testing the objects.
console.log(grd.getComponent('body') === grd.getComponent('foot')); // false, ok!
console.log(grd.getComponent('body').getComponent('comp') === grd.getComponent('foot').getComponent('comp')); // true?? should be false!
}
</script>
<style type='text/css'>
.grd { border: 1px solid black }
.grd-part {
height: 25px;
padding: 12px;
border-bottom: 1px solid black;
}
.grd-part:last-child { border:none }
.grd-part .comp {
background: black;
height: 25px;
}
</style>
</head>
<body>
<div id='grd'></div>
</body>
If you copy and past this code into a html document you will see the problem. The yellow rectangle should be inside of the red rectangle!
Anyone knows what happens?