Reputation: 449
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?
Upvotes: 5
Views: 70
Reputation: 1856
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
Upvotes: 2
Reputation: 4998
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();
Upvotes: 0