5

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);
4

4 回答 4

2

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();
于 2013-09-17T19:07:12.377 回答
1

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

于 2013-09-17T19:09:40.413 回答
0

There are situations where "classes" are useful, but I think you can get away with a simple object here.

var items = {}
items.yspeed1 = {}
items.yspeed1.name = 'Yellow Upgrade';
items.yspeed1.price = 50;
items.yspeed2 = {};
items.yspeed2.name = 'Blue Upgrade';
items.yspeed2.price = 25;

var newitem = document.createElement('button');
newitem.innerHTML = items.yspeed1.name;
shop.appendChild(newitem);
于 2013-09-17T19:09:25.680 回答
0

if your looking to use a class based approach here's one using prototypes

Item Class:

function YSpeedItem(name, price)
{
  this.name = name;
  this.price = price;
}

YSpeedItem.prototype.getName = function()
{
  return this.name;
}

YSpeedItem.prototype.getPrice = function()
{
  return this.price;
}`

main code

var yspeed1 = new YSpeedItem("Yellow Upgrade", 50);
var yspeed2 = new YSpeedItem("Blue Upgrade", 25);
itemsList = [];
itemsList.push(yspeed1);
itemsList.push(yspeed2);

var newitem = document.createElement('button');
newitem.innerHTML = items[0].getName;
shop.appendChild(newitem);

more info here http://www.phpied.com/3-ways-to-define-a-javascript-class/

于 2013-09-17T19:23:51.257 回答