JS Classes and This

I'm curious if there is a way to avoid using arrow functions for methods you want to keep bound to the instance. For example,
class Pog{

works = () => console.log(this)

notworks(){
console.log(this)
}
}

const pog = new Pog()
const works = pog.works
const notworks = pog.notworks

works() // Pog {...
notworks() // undefined
class Pog{

works = () => console.log(this)

notworks(){
console.log(this)
}
}

const pog = new Pog()
const works = pog.works
const notworks = pog.notworks

works() // Pog {...
notworks() // undefined
63 Replies
Samathingamajig
the annoying way is
class Pog{
constructor() {
this.works2 = this.works2.bind(this);
}

works = () => console.log(this)

notworks(){
console.log(this)
}

works2() {
console.log(this);
}
}
class Pog{
constructor() {
this.works2 = this.works2.bind(this);
}

works = () => console.log(this)

notworks(){
console.log(this)
}

works2() {
console.log(this);
}
}
benten
benten2y ago
I know I can do const notworks = pog.notworks.bind(pog) but thats way worse than an arrow fn
Samathingamajig
what do you have against using arrow functions?
benten
benten2y ago
I think they're less readable But thanks, works2 is what I was looking for i guess
Jon Higger (He / Him)
I don't think many people would agree with that sentiment if the alternative to arrow functions is manually binding the this keyword IMO
benten
benten2y ago
Yeah it feels icky
Jon Higger (He / Him)
I mean it's probably good to learn some of the outdated JS stuff so that way you get to know the gotchas in case you're in a codebase with it.
benten
benten2y ago
do people just...always use arrow functions in classes then?
Jon Higger (He / Him)
pretty much I think
benten
benten2y ago
fair enough
Jon Higger (He / Him)
I also think (I could be wrong), in typescript it does that for you So I'll see the ES5 syntax in typescript more often
benten
benten2y ago
no i was running into an issue with this in ts
Jon Higger (He / Him)
interesting I know notworks works in that example, maybe it's a version thing?
benten
benten2y ago
Well, that works but the example would actually be calling
const foo = a.notworks
foo() // undefined
const foo = a.notworks
foo() // undefined
Not sure if it's a TS thing tho, the difference is that notworks() assigns the method to the prototype and works = () => assigns the method to the instance I've literally gone years without knowing how this works in js lol
Want results from more Discord servers?
Add your server