gpt4 book ai didi

javascript - 简单继承

转载 作者:行者123 更新时间:2023-11-29 15:49:40 25 4
gpt4 key购买 nike

我正在尝试来自 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 | 105 | 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);

为什么我没有得到以下信息?

1 | 105 | 10

最佳答案

这只是您通过 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());
}
}

关于javascript - 简单继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7183975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com