skip to Main Content

I’m new to JS and I don’t understand why this code is not working?

I want to call a class every time the page is loaded or refreshed.
To test this I added the initialises method to the constructor.
Unfortunately I get this error and I don’t understand why:

script.js:16 Uncaught TypeError: SinkShip is not a function
    at window.onload 

This is my .js Code so far.

class SinkShip{

    constructor(){
        this.initialies
    }

    initialies(){
        alert('it works');
    }

}

window.onload = (event)=>{
    console.log('HIIIII');
    let SinkShip;
    SinkShip = new SinkShip();
};

2

Answers


  1. In the local scope of your function, SinkShip refers to the local variable not the class. To fix use different name for a variable i.e. lowercase sinkShip :

    class SinkShip {
    
      constructor() {
        this.initialies();
      }
    
      initialies() {
        alert('it works');
      }
    
    }
    
    window.onload = (event) => {
      console.log('HIIIII');
      let sinkShip = new SinkShip();
    };
    Login or Signup to reply.
  2. You are "overriding" your class SinkShip with your variable SinkShip.

    Replace let SinkShip with let sinkShip

    class SinkShip {
      constructor() {
        this.initialies();
      }
    
      initialies() {
        alert("it works");
      }
    }
    
    window.onload = (event) => {
      console.log("HIIIII");
      let sinkShip;
      sinkShip = new SinkShip();
    };
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search