2011-08-25 66 views
3

我從http://ejohn.org/blog/simple-javascript-inheritance/嘗試簡單的繼承,我有以下代碼:簡單的繼承

var resources = []; 

var Entity = Class.extend({ 
    pos : { 
     x: 0, 
     y: 0 
    }, 
    init : function(x, y) { 
     this.pos.x = x; 
     this.pos.y = y; 
    }, 
    toString : function() { 
     return this.pos.x + ' | ' + this.pos.y; 
    } 
}); 

var bFunc = Entity.extend({ 
    init : function(x, y) { 
     this._super(x, y) 
    } 
}); 

var cFunc = Entity.extend({ 
    init : function(x, y) { 
     this._super(x, y) 
    } 
}); 

var Func = Class.extend({ 
    init : function() { 
     this.b = new bFunc(1, 10); 
     resources.push(this.b); 
     this.c = new cFunc(5, 10); 
     resources.push(this.c); 
    }, 
    print : function() { 
     for(var i in resources) { 
      console.log(resources[i].toString()); 
     } 
    } 
}); 

var func = new Func(); 
func.print(); 

當我運行上面,我看到這個控制檯:

 
5 | 10 
5 | 10 

但我設置:

this.b = new bFunc(1, 10); // 1, 10 
resources.push(this.b); 
this.c = new cFunc(5, 10); // 5, 10 
resources.push(this.c); 

爲什麼我沒有得到以下內容?

 
1 | 10 
5 | 10 

回答

1

這只是你的迭代(for var i in resources)。這不是數組索引迭代,即枚舉對象。

所以嘗試:

print : function() { 
     for(var r in resources) { 
      console.log(r.toString()); 
     } 
    } 

否則,數組的索引符號,你可以這樣做:

print : function() { 
     for(var i = 0; i < resources.length; i++) { 
      console.log(resources[i].toString()); 
     } 
    } 
+0

感謝您的回覆mrjoltcola,但我嘗試你的榜樣的。 第一張:

 0 1 
第二張:
 5 | 10 5 | 10 
vuohu

+0

什麼樣的對象是「資源」?枚舉對象的屬性時,您將獲得所有屬性。不僅僅是存儲在其中的項目。所以我推薦第二種形式。 – codenheim

+0

資源是我所有的類(b,c)和我用循環調用所有我的類從資源打印,但如果是一個類集(this.b = new bFunc(1,10)) - 一切都好,但如果更多所有Class get的最後一個Class x,y(如果是一個Class print - 1 | 10如果兩個Class帶有x和y 5 5 | 10 print - 5 | 10,5 | 10並且如果帶有x和y的15 Class 15和15以及三類打印 - 15 | 15,15 | 15,15 | 15。 – vuohu