A brief review
Let's start with a summary of what we have discussed in the past few lessons.
We know that there is a this
keyword for JavaScript functions. When used in an object, it refers to the current instance of that object.
1let user = {
2 name: "John",
3 hi() {
4 console.log(`Hello, ${this.name}!`);
5 },
6};
7
8user.hi();
1Hello, John!
Unlike the this
keyword in other programming languages, JavaScript allows this
to exist outside of an object, which enables us to build constructor functions like this:
1function User(name) {
2 this.name = name;
3 this.hi = function () {
4 console.log(`Hello, ${this.name}!`);
5 };
6}
7
8let user = new User("John");
9
10console.log(user.name);
11user.hi();
1John
2Hello, John!
Constructor functions are used to programmatically create objects. You can create both properties and methods with a constructor function.
There are two special properties in objects called getters and setters. As the name suggests, they are used to get or set property values.