Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

calling values with this.property vs object.property

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading