Asteria
Asteria

Reputation: 330

JavaScript append text using arrays

I'm attempting to reuse the code from here Edit a variable within an array to create something simmilar but less complex.

I made the 'working' function:

var WorkT = function(gain,loss,message) {
    coins += this.gain;
    coins -= this.loss;
    this.message = message;
}


workT1 = new WorkT(30,0,'<span class="red">+ 30 Gold Coins');
workT2 = new WorkT(15,0,'<span class="red">+ 15 Gold Coins');
workT3 = new WorkT(80,0,'<span class="red">+ 80 Gold Coins');
workT4 = new WorkT(1,0,'<span class="red">+ 1 Gold Coin');

WorkTs = [workT1,workT2,workT3,workT4];

And I'm trying to call it later on in my code with this:

$('#output').html(WorkTs[Math.floor(Math.random() * 4)].WorkT()); 

But, when I click the button, nothing changes. Can anyone tell me why?

Upvotes: 0

Views: 44

Answers (2)

nisargjhaveri
nisargjhaveri

Reputation: 1509

There are lots of errors in your code.

  1. What is the coins in the WorkT Constructor? Is it a global variable, or you wanted to do this.coins?
  2. this.gain and this.loss does not exist. They are just gain and loss.
  3. There is no function called WorkT in the class WorkT. You probably want to define the function, too.

Here is how the code will look like, assuming coins is a global variable.

var WorkT = function(gain,loss,message) {
    coins += gain;
    coins -= loss;
    this.message = message;

    this.work = function(){
        //Do something here.
    }
}

And,

$('#output').html(WorkTs[Math.floor(Math.random() * 4)].work()); 

Upvotes: 0

Yoann
Yoann

Reputation: 3070

Your WorkT instances have no WorkT() function.

You need to declare a function named WorkT (or else) inside your WorkT 'class' :

var WorkT = function(gain,loss,message) {
    //...
    this.work = function () {
        //Do Something.
    }
}

Or you won't be able to call it on your instances :

$('#output').html(WorkT[Math.floor(Math.random() * 4)].work()); 


It all depends on what you're trying to achieve here.

Upvotes: 2

Related Questions