Original post at: https://siderite.dev/blog/in-class-members-which-functions-not-defined-unles/
You are writing some Javascript code in the browser and you create classes, then you create some methods, which you see have some issue with the "this" keyword by default if you use the standard method declaration so you end up doing something like this:
// instead of myMethod() { ... }
myMethod=()=>{
const myClass=this;
}
And this (pardon the pun) works here. Imagine my surprise when I did something that seemed identical:
// instead of myMethod() { ... }
myMethod=()=>{
debugger;
}
And then I tried to see what "this" was in the Chrome Developer Tools. It was "undefined". Why?!
Long story short, I then tried this (heh!) and it worked:
// instead of myMethod() { ... }
myMethod=()=>{
const myClass=this;
debugger;
}
The moral of the story is that "this" is not declared unless used in code. Probably a browser optimization. Hope it saves you the ten minutes it took me to understand what was going on, after I've started doubting my entire JavaScript expertise and the entire design of my app.
Top comments (0)