简体   繁体   中英

Why isn't this.key working properly in JavaScript?

 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?

When using arrow functions, it uses lexical scoping meaning that it refers to it's current scope and no further past that, ie, 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM