5

let student = {
    

fname: "Carlos",
    lname: 'Dubón',
    sayHi(){
        alert(`Hi my name is ${this.fname}`);
    },
    sayBye: function() {
        alert(`Bye ${this.fname}`);
    },
    sayHiAgain: ()=> {
        alert(`Hi my name is ${this.fname}`);
    }
}

student.sayHiAgain();

I'm new to OOP in Javascript, I understand that the 3 ways in which I wrote a method work exactly the same.

student.sayHi(); works and shows up the alert => "Hi my name is Carlos"

but student.sayHiAgain(); shows up the alert => "Hi my name is undefined"

What am I missing?

karel
  • 3,880
  • 31
  • 37
  • 42
Carlos Daniel
  • 369
  • 1
  • 9
  • 1
    Does this answer your question? [Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable) – ASDFGerte Jul 24 '20 at 02:45
  • Does this answer your question? [Methods in ES6 objects: using arrow functions](https://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions) – holydragon Jul 24 '20 at 02:49

2 Answers2

2

When using arrow functions, it uses lexical scoping meaning that it refers to it's current scope and no further past that, i.e., binds to the inner-function and not to the object itself.

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill suited as methods, and they cannot be used as constructors.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Harben
  • 1,430
  • 1
  • 9
  • 16
0

Arrow functions have no “this”

Arrow functions are special: they don’t have their “own” this. If we reference this from such a function, it’s taken from the outer “normal” function.

let student = {
  fname: "Carlos",
  lname: "Dubón",
  sayHi: function () {
    console.log(`Hi my name is ${this.fname}`);
  },
  sayBye: function () {
    console.log(`Bye ${this.fname}`);
  },
  sayHiAgain: function () {
    console.log(`Hi my name is ${this.fname}`);
  },
};

student.sayHiAgain();

Arrow function expressions

Mario
  • 4,117
  • 1
  • 22
  • 39