Confused why using this.name returns undefined property value


#1

Apologies if this should have been posted elsewhere - I couldn’t find an area of the forums meant for the “Introduction to Javascript: Objects” lesson found here:

https://www.codecademy.com/courses/learn-javascript-objects/lessons/objects/exercises/this?action=lesson_resume&course_redirect=introduction-to-javascript

My confusion stems from trying to find out why this code:

const person = {
  name: "David",
  age: 35,
  weekendAlarm: 'No alarms needed',
  weekAlarm: 'Alarm set to 7AM',
  sayHello: () => {
    return `Hello, my name is ${this.name}`;
  },
  sayGoodbye(){
    return 'Goodbye!';
  },
};

console.log(person.sayHello());

Has a console output of:

Hello, my name is undefined

While this code:

const person = {
  name: "David",
  age: 35,
  weekendAlarm: 'No alarms needed',
  weekAlarm: 'Alarm set to 7AM',
  sayHello: () => {
    return `Hello, my name is ${person.name}`;
  },
  sayGoodbye(){
    return 'Goodbye!';
  },
};

console.log(person.sayHello());

Has the actual desired output of this:

Hello, my name is David

The instructions ask me to use “this” to interpolate my name into the string for the output, but the first set of code wasn’t cooperating and I changed it to the second set of code which the lesson then accepted as correct. Anybody explain to me why this.name isn’t pulling the property value as the lesson seems to indicate it should be, but person.name grabs it without complaint?


8.15 - The This Keyword! (Yes ... another one!)
#2

the scope of this refers to the windows object, not to person object, because arrow syntax is not for methods, doing it causes scope issues with this, see here:

mdn - methods

The method syntax is shorter for es6, but not with arrow syntax, that is for functions.


#3

Ah I didn’t even notice that I still had that one wrapped in arrow syntax, time for a break and some lunch. Thanks!


#4

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