This is probably an easy-to-solve question but I do not look for solutions, I look for explanations. So I’ve been working on understanding Objects in JavaScript better and played around two days now with Objects. But in my learning Journey I dont seem to find the answer to this problem. Why will JavaScript allow me to call the values of the property if I use this.property but not if I use object.property. Heres an example to illustrate my problem more specifically.
class Car {
constructor(type, year, colour) {
this.type = type;
this.year = year;
this.colour = colour;
}
alerter() {
alert(Car["type"] + " " + Car.year + " " + this.colour);
}
}
const car1 = new Car("Audi", "12 Years", "Black");
car1.alerter();
Results:
undefined undefined Black
I know if I use this.property I will reference to my object, but wouldn’t I reference to my Object if I use Object.property?
Any help will be gladly appreciated!
>Solution :
this, in that context, represents the object the method is called on. (further reading)
Car is a class (which is akin to a template for making objects) and is not the same as Car1 (an object made from that class) which has the year property.