Creating a class in JS OOP

Viewed 96

Can You help with this thing that I need to figure out. I started learning Js with OOP but I am kind of stuck with this, where am I making a mistake. This is the assignment I have to figure out

Create a class Car with a property that holds a number of doors and one method that prints the number of doors to the console.

class Car { 
    constructor(doors){
     this.doors=doors
     console.log(doors)
    }
}
2 Answers

you need to create a method in the Car class to print the number of doors and then you need to instantiate the class with a given number of door & then call that method on it.

class Car { 
    constructor(doors){
     this.doors = doors;
    }
    print(){
        console.log(this.doors);
    }
}

const bmw = new Car(4);
bmw.print()

Hey

Yeah no problem :)

class Car {
    constructor(doors) {
        this.doors = doors;
    }

    printDoors() {
        console.log(this.doors);
    }
}

In JS OOP you have to define your member variables within the constructor by using the this keyword. To access your variables somewhere else in the class you also have to use `this.

The printDoor() function has to be defined at its own to call it later on like this:

const numberDoors = 4;
const myCar = new Car(numberDoors);
myCar.printDoors();
// expected output: 4
Related