0

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 don’t 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. Here’s 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!

user3840170
  • 26,597
  • 4
  • 30
  • 62
  • 2
    understand `static` from mdn doc [static](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static) – Anil kumar Feb 28 '23 at 15:21
  • 3
    Note that in idiomatic JS, variable names starting with a capital letter are reserved for classes and constructor functions. You should name your instance variable `car1` not `Car1`. – Quentin Feb 28 '23 at 15:23
  • @Anil kumar thank you very much for your answer! So if I've understand it right using static is telling the program that I use the Class as the property rather than the object. If this is the case that is pretty dope!! But I'm wondering what the use cases would be for static. Would love an answer!!! – ProgramFreak Feb 28 '23 at 15:41

1 Answers1

4

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335