jeudi 13 février 2020

Why `this` inside if statement in a function that is in an object is needed but not outside? JavaScript [duplicate]

Code looks like this

let car = {
    make: "bmw",
    model: "520",
    isStarted: false,
    start: function() {
        isStarted = true
    },
    drive: function() {
        if (isStarted) {
            console.log("I am driving away....")
        } else {
            console.log("I am still false")
        }
    }
}

car.start();
car.drive();

I read that since isStarted is part of an object i need to use this to tell JavaScript which isStarted i am thinking of. But car.start() executes like it knows it is isStarted from the object without needing this keyword, unless

....
start: function() {
    if(!isStarted) {
       isStarted = true
    }
}
....

isStarted is placed inside if and now i need if (this.isStarted) because it throws undefiend.

Aucun commentaire:

Enregistrer un commentaire