我想創建一個使用javascript原型繼承的網格,但有一個問題,我不明白。在代碼的某些部分,「新」關鍵字似乎不起作用。在Javascript Instanciation意外的結果
這很難解釋,所以代碼如下,我把意見放在要點上。
<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>
如果您將此代碼複製並過濾到html文檔中,您將會看到問題。黃色矩形應該在紅色矩形內!
任何人都知道會發生什麼?
謝謝!現在我知道如何使用Object.create進行繼承了!我已經嘗試過但沒有成功。謝謝你的回答,它解決了我的問題。我也會看到關於ES6的。我不知道它已經可用了!謝謝:) – jairhumberto 2014-08-27 15:21:34
我認爲任何瀏覽器都不支持類語法,但有些轉換工具會將其轉換爲有效的ES5代碼。例如http://www.phpied.com/writing-es6-today-with-jstransform/ – 2014-08-27 15:22:37