I know this is very basic, but why does x return undefined in this code block? Is there a way to define a property and immediately use it to set another property?
var grid = {
x : 75,
y : 75,
location : [grid.x, grid.y],
init : function () {
console.log(grid.location[0]);
}
}
You can't use the variable to access properties of the object before the object has been assigned to the variable. While the object is created, the variable grid
is still undefined. While the object is being created, you don't have any reference to it.
You can use the properies once the object has been assigned to the variable:
var grid = {
x : 75,
y : 75,
init : function () {
console.log(grid.location[0]);
}
}
grid.location = [grid.x, grid.y];
You can also wrap this in a function expression to get code that returns the complete object:
var grid =
(function(){
var obj = {
x : 75,
y : 75,
init : function () {
console.log(grid.location[0]);
}
};
obj.location = [obj.x, obj.y];
return obj;
})();