mercredi 12 mai 2021

Logic inside a basic class method not behaving as expected

Fooling around with Classes trying to understand them better and I've found myself stuck with what should otherwise be extremely basic.

The code below is basically just a class extending another and me trying them out. My issue has to do specifically with the logic within the Animal method danger(dangerLvl).

The way it's written just below works as expected:

class Animal {
    constructor(name, age, dangerLvl) {
        this.name = name;
        this.age = age;
        this.dangerLvl = dangerLvl;
    }
    danger(dangerLvl) {
        if (dangerLvl != 0) {
            return `${this.name} is dangerous!`
        } else {
            return `${this.name} is docile :)`
        }
    }
}

class Feline extends Animal {
    hiss() {
        return `${this.name} hisses threateningly!`
    }
}

const sissi = new Feline("Sissi", 5, 1);

sissi.danger();
// returns "Sissi is dangerous!"

What I don't get is the behavior of the method danger(dangerLvl) when written like this:

    danger(dangerLvl) {
        if (dangerLvl >= 1) {
            return `${this.name} is dangerous!`
        } else {
            return `${this.name} is docile :)`
        }
    }

const sissi = new Feline("Sissi", 5, 1);

sissi.danger();
// returns "Sissi is docile :)" <===== which is NOT expected. This is what I don't get.

Not exactly sure how I've managed to get to a point where I somewhat get async functions, callbacks and prototypes but can't figure out something as basic as this. Quite frustrating to say the least.

In my mind I should even be able to write it this way but clearly I'm missing something...

    danger(dangerLvl) {
        if (dangerLvl >= 1) {
            return `${this.name} is dangerous!`
        }
        return `${this.name} is docile :)`
    }

Thanks.

Aucun commentaire:

Enregistrer un commentaire