0

I would like to know why this example shows the following behavior. If we write:

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

console.log(person.sayHello());

let friend = {
  name: 'Bruno'
};

friend.sayHello = person.sayHello;

console.log(friend.sayHello());

We get as output:

Hello, my name is undefined
Hello, my name is undefined

And if we try to use:

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

console.log(person.sayHello());

let friend = {
  name: 'Tori'
};

friend.sayHello = person.sayHello;

console.log(friend.sayHello());

We see:

Hello, my name is ENoy
Hello, my name is ENoy

In Java I have seen various ways to get it done:

Java - get the current class name?

In JavaScript I have seen the constructor:

Get name of object or class

But I think in the previous link we get the method which instantiated the object we would like in this topic get the variable from the object where the function is declared.

Stphane
  • 3,368
  • 5
  • 32
  • 47
Yone
  • 2,064
  • 5
  • 25
  • 56
  • You would need to write either `sayHello: function () {` or `sayHello() {` – t.niese Mar 15 '18 at 15:31
  • 1
    You want to declare the function as `sayHello: function () ...`, then it works as you expect. See difference of behaviour wrt. `this` between arrow functions and regular functions. – deceze Mar 15 '18 at 15:31
  • when using the fat arrow `=>` you lost the scope of `this`. In that function console log `this` to see. – HolyMoly Mar 15 '18 at 15:33

0 Answers0