How to extend a class correctly in js

Good evening everyone :slight_smile:
I am working on this task and have a question.

  1. Create 1 parent and 2 inherited classes: Vehicle(private manufacturer, public name) and Car(private type (Crossover, Sport, Sedan)) Motorcycle(mototype(cross, sport)).

Vehicle has a getter Name returning name. Car has getter+setter for type. Motorcycle has getter+setter for motortype. Create 2 instances of car and motorcycles, test their methods.

so far i created this code

if i want to get the name from new car or new motorcycle i recive an undifined.
Where is the error i can not find it? I tried to change the constructors.

// task 1

class vehicle {
#manufacturer;
constructor(manufacturer) {
this.#manufacturer = manufacturer;
}

get name() {
return this.name;
}
}

class car extends vehicle {
#type;
constructor(manufacturer, name, type) {
super(manufacturer, name);
this.#type = type;
}

get type() {
return this.#type;
}

set type(value) {
if (value.length > 3) this.#type = value;
}
}

class motorcycle extends vehicle {
#motortype;
constructor(manufacturer, name, motortype) {
super(manufacturer, name);
this.#motortype = motortype;
}

get motortype() {
return this.#motortype;
}

set motortype(value) {
if (value.length > 3) {
this.#motortype = value;
}
}
}

const e = new motorcycle(‘audi’, ‘a3’, ‘sport’);
console.log(e.motortype);
e.motortype = ‘supersport’;
console.log(e.motortype);

const d = new car(‘bmw’, ‘m2’, ‘cool’);
console.log(d.type);
d.type = ‘lazy’;
console.log(d.type);

if i want to get the name from new car or new motorcycle i recive an undifined.
Where is the error i can not find it? I tried to change the constructors.

Where are you storing the name property? You are including it in the super:

constructor(manufacturer, name, type) {
        super(manufacturer, name);
        this.#type = type;
}

But I don’t see where the vehicle constructor is doing anything with it. That constructor only takes one arg.

yes you are right! i changed that to

class vehicle {
#manufacturer;
name;

constructor(manufacturer, name) {
this.#manufacturer = manufacturer;
this.name = name;
}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.