TransWikia.com

why this.key is not working properly in javacript?

Stack Overflow Asked by Carlos Daniel on September 25, 2020

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?

2 Answers

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

Correct answer by Harben on September 25, 2020

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

Answered by Mario on September 25, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP