I’m struggling to get my head around the way JS uses the ‘this’ keyword.
In every other programming language I’ve used, if you use ‘this’ in a function in a class instance you get that class instance, but in JS I just get the window object.
I’ve tried the following but no dice:
// In constructor
this.function = this.function.bind(this);
Why does ‘this’ behave so weirdly in JS and how can I get the current class instance?
I’m struggling to get my head around the way JS uses the ‘this’ keyword.
Yep, join the club.
In every other programming language I’ve used, if you use ‘this’ in a function in a class instance you get that class instance, but in JS I just get the window object.
Yeah, remember that this (at least in JS) is defined not at compile time but at runtime, depending on from where it is called. This article might help.
I don’t know why the binding you show doesn’t work - I think we’d need to see more of the code.
Why does ‘this’ behave so weirdly in JS and how can I get the current class instance?
It’s a different language. Why doesn’t Java handle strings the same way C does? It’s a different language.
I think it’s good to remember that JS is not OOP, it is OOP-ish. And also it’s not FP, it’s FP-ish. They decided to use certain aspects of some of those paradigms and not others, trying to make something new. Was it the right thing to do? That’s subjective, but JS seems to be doing OK.
But yeah, this is a difficult concept for people, especially if they’ve done a bunch of OOP.