Understand how this function notation differs


#1

Hello,

I came upon this issue while doing this section, the top portion of code, gives, ‘Hello, my name is undefined’.

If I, instead of using this and use the name of the object, like: person.name, I get the correct output.

The portion of code below the first, gives the supposed answer, ‘Hello, my name is Drew’.

I must be not understanding, because I thought that these two ways of writing a function were basically the same?

let person = {
name: ‘Drew’,
age: 28,
weekendAlarm: ‘No alarms needed’,
weekAlarm: ‘Alarm set to 7AM’,

sayHello: () => {
return Hello, my name is ${this.name};
},

sayGoodbye() {
return ‘Goodbye!’;
}
};

let person = {
name: ‘Drew’,
age: 28,
weekendAlarm: ‘No alarms needed’,
weekAlarm: ‘Alarm set to 7AM’,

sayHello: function() {
return Hello, my name is ${this.name};
},

sayGoodbye() {
return ‘Goodbye!’;
}

};


#2

We cannot use arrow functions as methods because they do not have a this object.

sayHello = function() {

};

or the new syntax…

sayHello () {
    return `Hello, my name is ${this.name}`.
}

#3

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