Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a class/object that can be referenced at multiple levels

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);
like image 582
TehBucket Avatar asked Oct 21 '22 00:10

TehBucket


2 Answers

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();
like image 78
iConnor Avatar answered Oct 27 '22 10:10

iConnor


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' };

like image 37
Eli Gassert Avatar answered Oct 27 '22 09:10

Eli Gassert