So here's my code:
var room = {
foo: [0, 1, 0, 0],
bar: {0: true, 1: false},
layers: [[开发者_JAVA百科this.foo, this.bar], [this.foo, this.bar]],
};
I'm creating a map data structure for a simple canvas game. The problem is my layers property comes up as undefined
for each element. How can I access foo and bar inside of layers properly to solve this?
var foo = [0, 1, 0, 0];
var bar = {0: true, 1:false};
var room = {
foo:foo,
bar:bar,
layers:[[foo, bar], [foo, bar]]
};
Edit after comment: I don't know that you will be able to do this without defining the inputs outside of the object literal, or not using object literal notation. Here is a working version without defining room using object literal notation:
function Room(){
this.foo = [0,1,0,0];
this.bar = {0:true, 1:false};
this.layers = [[this.foo, this.bar], [this.foo,this.bar]];
}
var room = new Room();
alert("result:"+room.layers[0][0]);
you can use a getter:
var room = {
foo: [0, 1, 0, 0],
bar: {0: true, 1: false},
get layers (){ return [[this.foo, this.bar], [this.foo, this.bar]]}
};
JSFiddle: http://jsfiddle.net/wLNEj/
精彩评论