Skip to content

Instantly share code, notes, and snippets.

@mariusschulz
Last active December 15, 2023 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariusschulz/e68330ca340d14341a8fff9a014a113c to your computer and use it in GitHub Desktop.
Save mariusschulz/e68330ca340d14341a8fff9a014a113c to your computer and use it in GitHub Desktop.
Code for my egghead.io course "Understand JavaScript's this Keyword in Depth"
// "use strict";
console.log(this === window);
function func() {
"use strict";
console.log(this === undefined);
}
func();
// "use strict";
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const person = Person("Jane", "Doe");
console.log(person);
console.log(window.firstName);
console.log(window.lastName);
function Person(firstName, lastName) {
console.log(this);
this.firstName = firstName;
console.log(this);
this.lastName = lastName;
console.log(this);
// return this;
}
const person = new Person("Jane", "Doe");
const person = {
firstName: "John",
sayHi() {
console.log(`Hi, my name is ${this.firstName}!`);
}
};
person.sayHi();
const person = {
firstName: "John",
sayHi() {
console.log(`Hi, my name is ${this.firstName}!`);
}
};
const greet = person.sayHi;
greet();
function sayHi() {
console.log(`Hi, my name is ${this.firstName}!`);
}
const person = {
firstName: "Jane",
lastName: "Doe"
};
sayHi.apply(person);
const person = {
firstName: "John",
sayHi() {
console.log(`Hi, my name is ${this.firstName}!`);
}
};
setTimeout(person.sayHi /* .bind(person) */, 1000);
const outerThis = this;
const func = () => {
console.log(this === outerThis);
};
func();
func.call(null);
func.apply(undefined);
func.bind({})();
const counter = {
count: 0,
incrementPeriodically() {
setInterval(() => {
console.log(++this.count);
}, 1000);
}
};
counter.incrementPeriodically();
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
sayHi() {
console.log(`Hi, my name is ${this.firstName}!`);
}
}
const person = new Person("John", "Doe");
person.sayHi();
class Person {
sayHi = () => {
console.log(`Hi, my name is ${this.firstName}!`);
};
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
const person = new Person("John", "Doe");
const greet = person.sayHi;
greet();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment