let person = {
fullName: 'Bob Loblaw',
sayHi: () => {
console.log(this);
console.log(`Hi ${this.fullName}`);
},
sayHello: function() {
console.log(this);
console.log(`Hello ${this.fullName}!`);
}
};
Let person represent an object in your global scope.
It has a property fullName, which equals 'Bob Loblaw', and two methods: sayHi and sayHello, that each console.log two values.
If you were to call both of these methods, what would each of them log and why?
person.sayHi() will log the window and Hi undefined.
The arrow function binds the context lexically with the window object.
Executing this.sayHi is equivalent to window.sayHi, which is undefined.
person.sayHello() will log the person object and Hello Bob Loblaw.
When a function is called as a method of an object, its this is set to the object the method is called on.