1

I have two ways to define sayHi method:

1. BoardMember.prototype.sayHi = ()=>{return `Hi, my name is ${this.name}. I am from ${this.homeState}, and I was trained in ${this.training}.`}

2. BoardMember.prototype.sayHi = function(){
  return `Hi, my name is ${this.name}. I am from ${this.homeState}, and I was trained in ${this.training}.`
}

When I try to call someBoardMember.sayHi(), the first one's this refers to the global object, window, while the second one refers to the someBoardMember, I don't really get why. Don't they have the same receiver? What makes this different??

Yingqi
  • 985
  • 2
  • 13
  • 24
  • 1
    It's due to you using an arrow function (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) – Dehli Jan 10 '20 at 19:52
  • It is because In Es6 arrow functions use lexical "this", You are technically targeting the window object when you use an arrow function as a method within an object. Here is some more info about it. (https://stackoverflow.com/questions/1047454/what-is-lexical-scope) – Ethan Franson Jan 10 '20 at 20:15

0 Answers0