I have read many, many ways of making makeshift classes in javascript. I'm trying to create a giant list of items, each with a variety of variables. I need to be able to call a certain object's properties from this list. The following code compiles, but when line 9 tries to access items.yspeed1.name, it creates the button with the name "undefined". I have no clue how to access a function's variables in javascript like this.
var itemslist = function(){
this.yspeed1 = function(){
this.name = 'Yellow Upgrade';
this.price = 50;
}
this.yspeed2 = function(){
this.name = 'Blue Upgrade';
this.price = 25;
}
}
var newitem = document.createElement('button');
newitem.innerHTML = items.yspeed1.name;
shop.appendChild(newitem);
Well, for a starters yspeed1
is a function
so you have to call it anyway, I think this might be the sort of thing you're looking for.
var itemslist = function(){
this.yspeed1 = {
name: 'Yellow Upgrade',
price: 50
}
}
This is just one way. other than that you'll have to create a
new items.yspeed1();
You use a class in JS when you are defining a reusable structure with state, i.e. you might have multiple copies (instances) of a class.
What you have is just a definition of a single object (single instance) with properties. So use that Javascript construct instead:
var itemslist = {
yspeed1: {
name: 'Yellow Upgrade'
, price: 50
}
, yspeed2: {
name: 'Blue Upgrade'
, price: 25
}
}
Now you have a single object with two properties -- yspeed1 and yspeed2. And those each have their own properties of name and price.
If you want to expand that object, just add to it, e.g. itemslist.yspeed3 = { hello: 'world' };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With