Skip to content

Instantly share code, notes, and snippets.

@gerrard00
Created January 31, 2024 20:35
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 gerrard00/a78f138e6414ecfe98a2ad6e8052d445 to your computer and use it in GitHub Desktop.
Save gerrard00/a78f138e6414ecfe98a2ad6e8052d445 to your computer and use it in GitHub Desktop.
this is evil
export class Foo {
constructor(name) {
this.name = name
}
DoIt() {
console.log(`Hello ${this.name}`);
}
}
const f = new Foo("Direct");
// works directly
f.DoIt()
// works in an arrow function because it's in a closure
// this is generally what you want to do
f.name = 'Closure'
const callbackLambda = () => f.DoIt()
callbackLambda();
// here we are getting the function, but we are explicitly binding it to an instance
f.name = 'Bound'
const callbackBound = f.DoIt.bind(f);
callbackBound();
try {
// here we are getting the function and not the method on our instance f
f.name = 'Function'
const callbackDirect = f.DoIt;
// goes boom
callbackDirect();
} catch (err) {
console.error('It went boom', err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment