Reputation: 2786
I'm making a game where I want to store the enemies as an object before loading them into the game.
var that = this;
this.enemies = {
that.redCar : document.getElementById('red'),
that.sportsCar : document.getElementById('sport')
}
But this gives me a syntax error. I thought that.redCar : document.getElementById('red')
in an object would be equal to that.redCar = document.getElementById('red')
outside of one.
Where am I going wrong?
Upvotes: 0
Views: 2229
Reputation: 9466
You seem to believe that it is necessary to declare the this
keyword when assigning properties to a JavaScript object.
While this may be true when defining an object's constructor, like so...
function MyClass() {
this.color = "blue";
}
var myObj = new MyClass();
...right now, this is not the case.
When you use the "object literal" syntax (var myObj = { /*properties...*/ };
), this
isn't required; in fact, it isn't allowed.
Here's how you should assign those properties:
this.enemies = {
redCar: document.getElementById('red'),
sportsCar: document.getElementById('sport')
};
Upvotes: 1
Reputation: 29221
Unless there is a different function scope than the one that you listed in your code, there is no need to use this
. Just declare an object literal:
enemies = {
redCar : document.getElementById('red'),
sportsCar : document.getElementById('sport')
}
// example reference
enemies.redCar.className += " active";
Also, be careful with this
. Unless you are using this
within the scope of a function, you are referring to the window object. Unless you are declaring the above code within a function scope that you have not stated, this
refers to the global object.
Upvotes: 0
Reputation: 59283
When you say this.enemies = { ... }
, you are declaring an Object literal that is inside of this
, i.e.:
this
enemies
redCar: ...
sportsCar: ...
It doesn't make sense to say that.redCar = ...
, because you are already inside enemies
. If you want to access it like
this.enemies.redCar
then you can just do this:
this.enemies = {
redCar : document.getElementById('red'),
sportsCar : document.getElementById('sport')
}
And if you want to access it like
this.redCar
then don't use enemies
at all, and just do
this.redCar = document.getElementById('red'),
this.sportsCar = document.getElementById('sport')
Upvotes: 4
Reputation: 2535
You have to use string
as an object key, thus that.redCar
is illegal.
Upvotes: 0
Reputation: 41
I think is better to declare the variable that as an object, no? You better try with:
var that = new Object();
Instead of:
var that = this;
Or what is the declaration of this?
Upvotes: -1