The this Keyword I - define method with arrow function


#1

this.name will be undefined if sayHello() method is defined below using arrow function.

let day = 'Monday';
let person = {
  name: 'Jim',
  sayHello: () => {
    return `Hello, my name is ${this.name}`;
  },
};

console.log(person.sayHello());

It works if replacing sayHello method to below:

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

Why is it?


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

because of what this is referencing, if we do:

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

we can see it refers to the current object, where as here:

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

refers to window in a browser.

what the value of this is, is determined by context.

If we look here:

we see this is es5 syntax:

var obj = {
  foo: function() {
    /* code */
  },
  bar: function() {
    /* code */
  }
};

this is es6 syntax:

var obj = {
  foo() {
    /* code */
  },
  bar() {
    /* code */
  }
};

so what you wrote here:

sayHello: () => {

edit thanks to @arellin0108, using arrow syntax will cause this not to bind to the object, but staying to default (window of browser), which can give unexpected behaviour, so is generally not recommended.


#3

Thanks to your hint !
Actually method can be defined using arrow function.
However, MDN document suggest not to use like this.
Because it will cause exactly the same problem I ran into: ‘this’ will not bind to the object calling the method.
Below is the reference.
MDN arrow function


#4

nice, you did more research, that is really impressive :slight_smile:

MDN always has documentation for html, css and JS. Always good to check things there

Well, it seems you completely understand it now :slight_smile:


#5

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