Review: Using JavaScript Objects

What is "this"?

You may have noticed something slightly strange in our methods. Look at this one, for example:

introduceSelf() {
  console.log(`Hi! I'm ${this.name[0]}.`);
}

You are probably wondering what "this" is. The this keyword refers to the current object the code is being written inside - so in this case this is equivalent to person. So why not just write person instead?

Well, when you only have to create a single object literal, it's not so useful. But if you create more than one, this enables you to use the same method definition for every object you create.

Let's illustrate what we mean by a simplified pair of person objects:

const person1 = {
  name: "Chris",
  introduceSelf() {
    console.log(`Hi! I'm ${this.name}.`);
  },
};

const person2 = {
  name: "Deepti",
  introduceSelf() {
    console.log(`Hi! I'm ${this.name}.`);
  },
};

In this case, person1.introduceSelf() it outputs "Hi! I'm Chris."; person2.introduceSelf() on the other hand, outputs "Hi! I'm Deepti.", even though the method's code is exactly the same in each case. This isn't hugely useful when you are writing out object literals by hand, but it will be essential when we start using constructors to create more than one object from a single object definition, and that's the subject of the next section.