AnswerBun.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!

Related Questions

Bluehost hosted React pages not found

0  Asked on November 10, 2021 by paul-lindberg

   

Change a view margins programmatically

4  Asked on November 10, 2021 by m-r_dino

     

React returning view from switch statement

1  Asked on November 10, 2021 by mattblack

   

Find string then return different row value Python

0  Asked on November 10, 2021 by newtothecrew

       

React JS – route does not pick the required Component

0  Asked on November 10, 2021 by nirjal-paudel

       

get character after space of array value on javascript

9  Asked on November 7, 2021 by riko-pramayudi

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP