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();
Unlike Java/C++, you don't declare fields. And, 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 theself
parameter-instead ofthis
- to reference to the current instance of the class)