Extending my comments with some additional information (emphasis are all mine).
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 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
A very good mention about it is on the Work with Classes trailhead:
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:
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