Skip to content

Instantly share code, notes, and snippets.

@maiastone
Last active February 25, 2017 23:21
Show Gist options
  • Save maiastone/16446a0a03c18d0a331379f09b734ec0 to your computer and use it in GitHub Desktop.
Save maiastone/16446a0a03c18d0a331379f09b734ec0 to your computer and use it in GitHub Desktop.
An exercise in regular function vs arrow function scope
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment