Skip to content

Instantly share code, notes, and snippets.

@sksundram
Last active February 9, 2021 12:04
Show Gist options
  • Save sksundram/4d01a30dd44f66c64ddc16a74ffa3362 to your computer and use it in GitHub Desktop.
Save sksundram/4d01a30dd44f66c64ddc16a74ffa3362 to your computer and use it in GitHub Desktop.
JavaScript Context (this) explained by Brad Schiff
{"scripts": [],"showConsole": true}
let person = {
firstName: 'Steve',
lastName: 'Smith',
driveCar() {
function iAmAFunctionNotAMethod() {
console.log(this); // this === window
}
iAmAFunctionNotAMethod();
console.log(`${this.firstName} ${this.lastName} is driving a car.`); // this === person
},
};
person.driveCar();
function breathe() {
console.log(`${this.firstName} ${this.lastName} just inhaled and exhaled.`);
}
breathe.call(person); // this === person
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment