In Java, why do people prepend fields with `this`?

前端 未结 16 2150
广开言路
广开言路 2020-12-20 11:18

When referencing class variables, why do people prepend it with this? I\'m not talking about the case when this is used to disambiguate from method

16条回答
  •  伪装坚强ぢ
    2020-12-20 11:28

    Something else to keep in mind is the language itself. You didn't mention Java specifically (though I'm assuming you didn't really have anything else in mind, so this comment is more FYI), but as the previous posters have mentioned already it is an excellent way of making code self-documenting to prevent mix-ups down the road when someone else starts modifying your code base.

    If you take PHP, though, the use of $this is typically required when referencing class variables. With differing rules between languages, it is often easiest to stick with the pattern that is common between them, a pattern which just so happens to be a very solid coding style throughout. It's easier for me to simply prepend this to everything than try to remember what language requires it and what language simply "prefers" it.

提交回复
热议问题