0

How Do I Change The Property?

var money = 100000 const car = { price:5000, bought:false, buy: function(){ if(car.bought == false && money > car.price){ money = money - car.price; // i want to change the bool bought to true but idk how } } }

24th Jan 2023, 1:48 PM
<! - - Ahmcl - - >
2 ответов
+ 3
this.bought = true; // "this" refers to the car object
24th Jan 2023, 2:25 PM
Lisa
Lisa - avatar
+ 1
Object members in JS can't be accessed by reference inside of the object's initialization, because the variable holding it is assigned a reference to the object AFTER all key/value pairs have been defined. So when you refer to `car.bought` from inside the object, the environment doesn't know yet that `car` holds a reference to `bought`, instead thinking `car` is an undefined variable. What you could do though is use the 'this' keyword instead, which refers to the object's context. const car = { price: 5000, bought: false, buy: function () { if (this.bought == false && money > this.price) { money = money - this.price; } } }
24th Jan 2023, 3:39 PM
ManuCoding