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

在构造函数中:

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。

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

其他回答

我在任何可能有歧义的地方都使用它(显然)。不只是编译器的模糊性(在这种情况下是必需的),还有查看代码的人的模糊性。

1 -常见的Java setter习语:

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

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

notifier.addListener(this);

我也倾向于在任何地方使用它,只是为了确保我们正在处理的是实例成员。

当你有很多开发人员在同一个代码库上工作时,你需要一些代码指南/规则。在我工作的地方,我们决定在字段、属性和事件上使用“this”。

对我来说,这样做很有意义,当你区分类变量和方法变量时,它使代码更容易阅读。

我使用它的时候,在一个函数中,接受了对同一类型对象的引用,我想完全清楚我引用的是哪个对象,在哪里。

例如

class AABB
{
  // ... members
  bool intersects( AABB other )
  {
    return other.left() < this->right() &&
           this->left() < other.right() &&

           // +y increases going down
           other.top() < this->bottom() &&
           this->top() < other.bottom() ;
  }
} ;

(vs)

class AABB
{
  bool intersects( AABB other )
  {
    return other.left() < right() &&
           left() < other.right() &&

           // +y increases going down
           other.top() < bottom() &&
           top() < other.bottom() ;
  }
} ;

AABB的right()指的是哪一个?这增加了一点澄清。