ES6 - Write Concise Declarative Functions with ES6

In the following Challenge: ES6 - Write Concise Declarative Functions with ES6, an example is used to describe how, with ES6, you can remove the function declaration and the end result will be the same. The example that’s used is as follows:

const person = {
  name: "Taylor",
  sayHello: function() {
    return `Hello! My name is ${this.name}.`;
  }
};

With ES6, you can remove the function keyword and colon altogether when defining functions in objects. Here’s an example of this syntax:

const person = {
  name: "Taylor",
  sayHello() {
    return `Hello! My name is ${this.name}.`;
  }
};

My question is as follows:

Since the template literal of this example is ${this.name}, would this example return as undefined?

The object it’s referring too, ${**this**.name}, does not exist in this example. The only object that exists in this example is const = person, so it seems to reason ${person.name}` would be the accurate template literal.

Am I correct? Is just a mistake in the example? Or, am I misunderstanding something about the ${**this**.name} template literal?

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

Challenge: ES6 - Write Concise Declarative Functions with ES6

Link to the challenge:

Did you try running the code? Open the browser console and run it.

In general when used inside a function, the this keyword refers to the object that calls it. It’s a special keyword.

In the example, this.name instructs the function to look at the object that called it (person) and retrieve the “name” property from it.

person.name would work too, but sometimes we want to access the object calling a function even when we don’t know what it’s called. In that case, we have to refer to it relatively with this.

Hope this helps!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.