我无法让这个工作:
var global_variables = {
players: []
};
var player = function(properties){
this.width = properties.width;
this.height = properties.height;
this.position = properties.position;
this.position.x = properties.position.x;
this.position.y = properties.position.y;
}
function load_players(){
global_variables.players.push(
[
new player(
{
width: 10,
height: 10,
position: {
x: 50,
y: 50
},
colour: '#ff0000'
}
)
]
);
}
function init(){
var ctx = load_canvas();
load_players();
for(a in global_variables.players){
var _this = global_variables.players[a];
alert(_this.colour);
}
}
alert(_this.colour)只是警告undefined。有什么想法吗?
答案 0 :(得分:2)
您从undefined
获得_this.colour
有两个原因:
colour
属性将其添加到构造函数:
this.colour = properties.colour;
然后从load_players()
函数中删除方括号:
function load_players(){
global_variables.players.push(
new player({
width: 10,
height: 10,
position: {
x: 50,
y: 50
},
colour: '#ff0000'
})
);
}
答案 1 :(得分:2)
init
for ... in ...
。使用常规循环或像我一样使用forEach
。 colour
属性设置为您的实例。以下是小提琴的代码:
var global_variables = {
players: []
};
var player = function(properties){
this.width = properties.width;
this.height = properties.height;
this.position = properties.position;
this.position.x = properties.position.x;
this.position.y = properties.position.y;
this.colour = properties.colour;
}
function load_players(){
global_variables.players.push(
new player(
{
width: 10,
height: 10,
position: {
x: 50,
y: 50
},
colour: '#ff0000'
}
)
);
}
init();
global_variables.players.forEach(function(player) {
alert(player.colour);
});
function init(){
load_players();
}
答案 2 :(得分:0)
当您推进global_variables.players
时,您正在推送一个包含new Player
对象的数组,而不是对象本身。
使用[]
时,您不需要.push
。
function load_players(){
global_variables.players.push(
new player({
width: 10,
height: 10,
position: {
x: 50,
y: 50
},
colour: '#ff0000'
})
);
}
P.S。不要将for...in
用于数组。只需使用正常的for
。
for(var a = 0, len = global_variables.players.length; a < len; a++){
var _this = global_variables.players[a];
alert(_this.colour);
}
P.P.S。您需要将this.colour = properties.colour;
添加到player
构造函数中。