+ 1
What (in Java) is the command "this." for?
I saw it in one of the Java Lessons example codes and I don't remember having learned about it yet. I searched through the lessons (the ones that are unlocked and so, obviously, already studied anyway) and found nothing. Could someone (or someones) please help me with this (pun not originally intended, but I like...THIS. 🤣😂😁🙄 Ahem, anyway, I was about to say that I have a vague recollection of it. I think it also exists in JavaSCRIPT but I don't remember what it did. Thanks in advance.
4 Respostas
+ 4
It provides context. Though your question is about Java, I have a way to make this clear in Javascript:
myfunc = document.getElementById;
myfunc("test")
ERROR: Illegal invocation
The error occurs because I have stripped "context" from getElementById() and myfunc() now has global context (which is illegal). To fix it, you have to bind its context (which then becomes the variable 'this' for myfunc):
myfunc = document.getElementById.bind(document);
If you could ask myfunc() what 'this' was, it would report DocumentObject. You can actually bind functions to other contexts, which is really useful but out of scope here.
In Java I believe it's the object context (so the object instance itself), but I should let someone who knows more Java answer that.
+ 3
this just means the acting object. it will be in the course later on too
+ 2
Oh, cool. Thanks to both of you for those answers. I did have a multifaceted question and, between the two of you, it was all fully answered. Thanks again!
+ 2
Another word sometimes used (e.g. Python) is 'self'.