-2

I am not sure why I'm getting undefined with the code below. I tried to declare a variable under the say method var _this = this and then console.log out _this.name but it did not work.

let dog = {
  name: 'doggo',
  sayName() {
    console.log(this.name)
  }
}
let sayName = dog.sayName
sayName()
iblamefish
  • 4,401
  • 3
  • 28
  • 43
Yama
  • 17
  • 1

1 Answers1

3
window.name="test";
sayName();//test

Executes the function in window context so this is window. You may want to keep the dog context either through passing it:

sayName.call(dog);//doggo

Or through keeping a bound function:

let sayName = dog.sayName.bind(dog);
sayName();//doggo
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120