我很好奇其他人是如何使用这个关键字的。我倾向于在构造函数中使用它,但我也可能在整个类的其他方法中使用它。一些例子:

在构造函数中:

public Light(Vector v)
{
    this.dir = new Vector(v);
}

在其他地方

public void SomeMethod()
{
    Vector vec = new Vector();
    double d = (vec * vec) - (this.radius * this.radius);
}

当前回答

我并不想这么说,但这并不重要。

认真对待。

看看那些重要的东西:你的项目,你的代码,你的工作,你的个人生活。它们中的任何一个都不会成功依赖于是否使用“this”关键字来限定对字段的访问。这个关键字不会帮助你按时发货。它不会减少bug,也不会对代码质量或可维护性产生明显的影响。它不会让你加薪,也不会让你在办公室花更少的时间。

It's really just a style issue. If you like "this", then use it. If you don't, then don't. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer's notions of what the "most aesthetically pleasing code" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn't like, or would have done differently. At some point some guy is going to read your code and grumble about something.

I wouldn't fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn't going to be scrutinizing how you initialize fields. He's just going to use your code, marvel at it's greatness, and then move on to something else.

其他回答

任何时候需要对当前对象的引用。

一个特别方便的场景是当对象调用一个函数并希望将自己传递给它时。

例子:

void onChange()
{
    screen.draw(this);
}

我只在绝对必要的时候使用它,即当另一个变量遮蔽另一个变量时。比如这里:

class Vector3
{
    float x;
    float y;
    float z;

    public Vector3(float x, float y, float z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }

}

或者像Ryan Fox指出的,当你需要把它作为参数传递时。(局部变量优先于成员变量)

黑C + +铝

我同意“非用不可”的说法。不必要地用它修饰代码并不是一个好主意,因为当你忘记这样做时,编译器不会警告你。这可能会给那些期待它一直在那里的人带来困惑,也就是说,他们必须考虑它。

那么,你什么时候会使用它呢?我只是看了一些随机的代码,并找到了这些例子(我不判断这些是好事还是坏事):

将“yourself”传递给一个函数。 将“你自己”分配给一个指针或类似的东西。 铸造,即上/下铸造(安全或其他),铸造constness等。 编译器强制消歧。

除非万不得已,否则不要用this。

不必要的冗长是有惩罚的。您应该努力使代码的长度恰好与需要的长度相同,而不是更长。

1 -常见的Java setter习语:

 public void setFoo(int foo) {
     this.foo = foo;
 }

2 -当调用以该对象作为参数的函数时

notifier.addListener(this);