Extending my comments with some additional information (emphasis are all mine).
To start with, there is no similarity between Java and JavaScript except for the word "Java" in JavaScript. Both are two different languages serving different purposes.
As for the this
keyword in two languages, below are some details.
By definition, Using the this
Keyword in Java is used:
Within an instance method or a constructor, this
is a reference to the current object — the object whose method or constructor is being called
The documentation further mentions as below.
The most common reason for using the this
keyword is because a field is shadowed by a method or constructor parameter.
In Java, you will always want to use this
whenever you have a name conflict of variables/methods to avoid shadowing.
As for best practice, it usually depends on the coding practices that different organizations adapt and how frequently you use it. In my experiences with Java, I have seen people preferring to use this
to explicitly call out if that was an instance variable vs. local variable. And some preferring not to have scenarios where there is a name conflict to avoid using this
.
Coming to Javascript, this
Keyword the link provided by @OleksandrBerehovskyi is a good starting point, which reflects the different behavior of the this
keyword. There are other resources which will help you to understand the significance of this
in Javascript specifically in ES6 modules used in LWC.
A very good mention about it is on the Work with Classes trailhead:
In an attempt to make JavaScript at least appear to work like a class-based language, ES6 introduced the class
keyword.
...
What is important to know is that even though the class
keyword is used, the underlying object created is still a function.
And then, the official documentation for this
on MDN mentions:
A function's this
keyword behaves a little differently in JavaScript compared to other languages.
...
In most cases, the value of this
is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called.
The only time when you can skip using this
in JS would be when you are say declaring local scoped variables. In all other cases you will end up using this
.
this
in JS, like in Java. Let's wait for answers from front-end ninjas. Meanwhile this on w3schoolsthis
is considered a bad practice in Java. You will normally want to usethis
whenever you want to avoid shadowing. Also it depends on the standards that you may be following. E.g., I have seen some company explicitly requiringthis
keyword before any check-ins. Coming to JS,this
in JS is entirely different than what is means in Java. The link provided by @OleksandrBerehovskyi is a good starting point as howthis
changes its behavior.