Do you use 'this' in front of instance var

2019-01-26 07:15发布

When accessing instance variables or properties of a class from within the class itself, do you prepend them with "this."?

17条回答
ら.Afraid
2楼-- · 2019-01-26 07:33

Only when required to distinguish from parameters, as in a setter or constructor. I consider its use in unnecessary cases to be "codejunk", analogous to Edward Tufte's chartjunk. Noise, instead of signal.

查看更多
做个烂人
3楼-- · 2019-01-26 07:35

Generally yes, I do. Communicating scope is an important aspect of readability. It distinguishes it from local variables, static methods, etc. It also communicates that the definition is "nearby".

Oh, and I only do it for public methods/properties. Those tend to be capitalized so this.Thing looks right. The internal view looks like the external view (myInstance.Thing). Private properties are often lowercase and so it's a less attractive idea for those.

It's not strictly necessary of course, and some people prefer it more terse. But it provides hints to me and other devs who might look at the code.

查看更多
唯我独甜
4楼-- · 2019-01-26 07:35

I do. I got in the habit back when Intellisense in Visual Studio wasn't as clever as it is these days.

I don't find it distracting, I suppose because I write a lot of Python and am used to seeing self everywhere.

查看更多
霸刀☆藐视天下
5楼-- · 2019-01-26 07:37

Yes, if I see this. I'm sure it is local and I do not need to look any further. If it isn't prefixed with this. (or maybe '_') I have to check if it is declared locally or in an ancestor or if it's a parameter or ...

All these checks take a little more time during debugging...

查看更多
一纸荒年 Trace。
6楼-- · 2019-01-26 07:38

I do a lot simply because it makes the autocompletion pop up.

查看更多
混吃等死
7楼-- · 2019-01-26 07:41

I only ever use a this. prefix in constructors or setters, primarily in the case where the passed parameters have the same name as the relevant member variables.

查看更多
登录 后发表回答