user9269916
user9269916

Reputation:

method not working from the class in HTML and JavaScript

I am trying to print out the gass method from the class Bil. I want it to print out when clicking a button in HTML. I get an error saying

Uncaught ReferenceError: gass is not defined at HTMLButtonElement.onclick 
(index.html:9). 

What could be the reason for this error?

 // My HTML Code  

<button onclick="gass()">Gass for Volvo</button>
<p id="test"></p>

<script src = "script.js"></script>

 //javascript code

class Bil{

    constructor(registeringsnr, merke, yearmodel, hastighet)
    {

        this.registeringsnr = registeringsnr;
        this.m = merke;
        this.yearmodel = yearmodel;
        this.hastighet = hastighet;
    }

gass() 
{
    var nyHastighetettergass = this.hastighet +10;

    return nyHastighetettergass;
}

 brems()
    {
        var nyHastighetetterbrems = this.hastighet - 10;

        return nyHastighetetterbrems;
    }
}

var volvo = new Bil(100,"volvo",2018,1);
var ferrari = new Bil(200, "ferrari", 2011, 0);
var lada = new Bil(300,"lada", 2012,0);

document.getElementById("test").innerHTML = gass();

Upvotes: 2

Views: 664

Answers (1)

cptwonton
cptwonton

Reputation: 468

In Javascript, class declarations are not hoisted, even though function declarations are. What this means is JS will not automatically hoist a class declaration to the top of the file - So you'll want to move you Bil class above your Button label.

Additionally, you'll want to create an instance variable of type Bil, and then call the gass() method on that instance variable within your button.

So to get this to work, your code should look something like this:

//declare Bil class at the top
var myBil = new Bil(v,x,y,z); //substitute v x y z for actual values like you did below your class declaration in the original code
<button onclick="myBil.gass()">Gass for Volvo</button>

Upvotes: 3

Related Questions