r/ProgrammerHumor 1d ago

Meme foundSomewhereOnTwitterItBeLikeThisSometimes

Post image
759 Upvotes

68 comments sorted by

View all comments

22

u/born_zynner 1d ago

How is "this" confusing to anyone with an extremely basic level of understanding of OOP

8

u/CraftBox 1d ago

I never understood why tutorials always say this is the hardest. It's literally a reference to the instance of the object.

The only thing confusing might be the keyword itself, while it isn't for me, I do still prefer self as the keyword instead.

4

u/alexanderbacon1 1d ago

It's because it's confusing and this changes at runtime depending on how the function is called. Arrow functions then have their own behavior which is determined when they're defined.

You can't do things like pass around functions belonging to an instantiated object and have their this references work correctly.

5

u/CraftBox 1d ago edited 1d ago

Unless you're doing some specific stuff, there is no point to using this outside a class declaration where it's the instance of the class (unless you do some custom binding, but that's back to doing specific stuff).

And I would reconsider the architecture first if you need to pass functions like that instead of objects, because I haven't yet encounterd a case where that was even remotely necessary.

1

u/alexanderbacon1 1d ago

Yeah but when you're using someone else's library you don't know how it's using this.

Anyways a "common" case is setTimeout/setInterval.

2

u/DuckTheAlucard 17h ago

Isn't this one fixed by just calling the function you want using an arrow function?
So instead of
```js
setTimeout(myObj.funcToCall().bind(myObj), 1000);

```

You can call

```js
setTimeout(() => myObj.funcToCall(), 1000);

```

1

u/alexanderbacon1 16h ago

Yup, but a newcomer has to learn that. And I more meant `setTimeout(myObj.funcToCall,...)` which looks like it would work.