2011-08-25 61 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