2

I am learning javascript. I used 'this' as below in javascript

let person = {
    name: 'Krishna',
    age: 35,
    sayHello() {
        return 'Hello, my name is ' + this.name;
     },
     sayHi: () => `Hi ${this.name}`
};

console.log(person.sayHello());
console.log(person.sayHi());

sayHello() function is properly getting 'this' as person object. But in shorthand function sayHi(), this is referring to global window object. Here I am calling sayHi() with person object. But not sure why this is not getting referred to window object. Can any one please explain why this in sayHi() is not getting initialized with person object?

kadina
  • 4,024
  • 3
  • 26
  • 60
  • 1
    Because you are calling it from a context where the global window is assigned to `this` and the arrow function (lamda) is capturing that passing it on to the call. – Igor Mar 20 '18 at 18:11
  • 3
    Hint: Don't use arrow functions for an object's methods. – tadman Mar 20 '18 at 18:11
  • 1
    Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Igor Mar 20 '18 at 18:12

5 Answers5

1

Arrow Functions lexically bind their context so this actually refers to the originating context.

{
  sayHi: () =>  // in context,
  sayHello() {
    // needs this to be in context
  }
}
Joe Warner
  • 2,928
  • 1
  • 12
  • 29
1

When you use sayHi: () => ... you are bounding this to the global context, not to person, thus you don't have a name property on the scope. This reading might help you.

josebreijo
  • 169
  • 1
  • 5
1

this inside the arrow function point to the same object as it did right before the arrow function was assigned (window).

If you really want to access the person object inside arrow function you have to do that directly by the the object name (person):

let person = {
    name: 'Krishna',
    age: 35,
    sayHello() {
        return 'Hello, my name is ' + this.name;
     },
    sayHi: () => `Hi ${person.name}`
};

console.log(person.sayHello());
console.log(person.sayHi());
Mamun
  • 58,653
  • 9
  • 33
  • 46
1

When you define sayHello(), you are leaving the this keyword unbound, to be assigned in the function invocation person.sayHello(). this refers to whatever is left of the dot in the invocation, namely person.

In sayHi(), you are binding the this keyword at the moment sayHi is defined. Since the context is not a function invocation but rather an object definition, the value of this is unknown and it defaults to the window object. Once you bind it in this way, it cannot be reassigned. When you run person.sayHi(), this refers to window and not person.

-1

In sayHello, you are returning the resulting string (which is calculating in context of the object (has this).

In sayHi, you are returning a function to console.log and then calling it where this is no longer defined because you're out of context.

J Livengood
  • 2,363
  • 1
  • 9
  • 23