The this
keyword
You must use the keyword this
inside a class to define/access properties (except for defining methods).
class Publication { setTitle(title) { this.title = title; } setAuthor(author) { this.author = author; } getTitle() { return this.title; } getAuthor() { return this.author; } print() { console.log(this.getTitle() + " by " + this.getAuthor()); } } const publication = new Publication(); publication.setTitle("CS280 Notes"); publication.setAuthor("Ali Madooei"); publication.print();
In JavaScript, unlike in Java/C++, you don't declare fields.
Moreover, you are not bounded to declare the attributes inside the constructor. However, for improved readability, I suggest that you always initialize your class attribute inside the constructor.
The JavaScript class
syntax is more similar to php/python's class definition. (Python classes, for instance, are constructed through a special method called __init__()
which uses the self
parameter-instead of this
- to refer to the current instance of the class)