Skip to content

Instantly share code, notes, and snippets.

@sielay
Last active January 25, 2021 10:43
Show Gist options
  • Save sielay/7050a677aee8d3301675fc0af52967e2 to your computer and use it in GitHub Desktop.
Save sielay/7050a677aee8d3301675fc0af52967e2 to your computer and use it in GitHub Desktop.
Most JS senior candidates didn't know why this won't work
function foo() {
setTimeout(function(){
this.magic();
}, 1);
}
foo.prototype.magic = () => console.log('magic');
new foo();
// it won't work. if you know why and look for VanillaJS/Angular position in London (Wimbledon) then send me your CV on ... (I don't work there anymore)
@keyserfaty
Copy link

this haven't got a magic method inside the setTimeout function since it's an other context.
This should work though:

function foo() {
let that = this;
  setTimeout(function(){
    that.magic();
  }, 1);
}

foo.prototype.magic = () => console.log('magic');
new foo();

@sielay
Copy link
Author

sielay commented Jan 25, 2021

Yes, you've spotted it. That was a honeypot question for candidates.

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