0

I have written the following code

<!DOCTYPE html>
<html>
<body>
    <h1 id="para"></h1>
    <script>                
        function Dice(sides) {  
            this.sides = sides; 
            this.roll = function() {                                            
                var randomNumber = Math.floor(Math.random() * this.sides) + 1;
                console.log(randomNumber);
            }                       
        }

        var dice = new Dice(6);
        var dice10 = new Dice(10);
    </script>
</body>
</html>

When I check the console, it's not printing random numbers & it seems my 'roll' method is not working. If I write code without roll method, it's working. But I want to enhance my skills in JS, so I am curious to know what's the problem with roll method in my constructor function.

2
  • 3
    Because you are not calling the function, just defining it. Commented Sep 27, 2015 at 13:48
  • Side note: "Dice" is plural. A single one of them is called a "die". Commented Sep 27, 2015 at 13:49

3 Answers 3

4

You need to call your roll function:

var dice = new Dice(6);
dice.roll();
Sign up to request clarification or add additional context in comments.

Comments

1

Try to call method of object after instantiation:

dice.roll();
dice10.roll();

You does not see roll()s result after call of constructor, because constructor defines method, not calls it (in your case).

Comments

0

Add line

dice.roll();

or

dice10.roll();

at the end.

The problem is you defined the constructor, but didn't call roll.

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.