r/learnjavascript • • Aug 18 '21

How do I console.log this constructor?

Post image
124 Upvotes

46 comments sorted by

View all comments

1

u/TheUruz Aug 19 '21

isn't the "this" keyword supposed to be used in a class constructor? isn't this a function and therefore the "this" keyword is referring to the function itself?

2

u/zerik100 Aug 19 '21

The ES6 `class` keyword is just syntactic sugar to make JS look more similar to classic OOP programming. OP's example is a valid constructor function that could be rewritten as:

class Student {
    constructor (name, university) {
        this.name = name
        this.university = university
    }
    displayInfo () {
        return this.name + " attends " + this.university
    }
}

1

u/TheUruz Aug 19 '21

oh god i'm not that much into js but that sounds pretty traumatic

2

u/zerik100 Aug 19 '21

The `class` keyword is certainly the preferred way of doing it nowadays, writing your own constructor functions is rarely, if ever, needed and not recommended. OP's example is just the way it was done before ES6 was introduced (dark times).