开发者

Simple Inheritance

I am trying Simple Inheritance from http://ejohn.org/blog/simple-javascript-inheritance/ and I have the following code:

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();

When I run the above, I see this in the console:

5 | 10
5 | 10

But I am set:

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

Why do I not get the following?

1 | 10
5 | 10


It is simply your iteration by for(var i in resources). That isn't an array index iteration, that is enumerating the objects.

So try:

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

Otherwise, with array index notation, you can do something like:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜