0

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?

2
  • 3
    You're overwriting your WorkT variable. Commented Oct 5, 2014 at 23:47
  • @YoannM whoops, you're right. forgot the 'S' in the array. Sorry, added that. Commented Oct 5, 2014 at 23:51

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I can't believe I over looked that!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.