2

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();
2
  • Try the following: Onclick=“new Bil(.....).gass()” you’re trying to execute the function gass that was defined within class Bil, therefore, gass function is out of scope from onclick of that button. Commented Jan 25, 2018 at 22:39
  • gass is a method of instances, so document.getElementById("test").innerHTML = volvo.gass();. Commented Jan 25, 2018 at 22:44

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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