在 Java 中,this.method() 和 method() 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6547310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:39:51  来源:igfitidea点击:

In Java, what is the difference between this.method() and method()?

javamethods

提问by nebkat

Is there any difference between calling this.method()and method()(including performance difference)?

调用this.method()method()(包括性能差异)之间有什么区别吗?

采纳答案by Peter Lawrey

The only time it matters is if you are using OuterClass.this.method()e.g.

唯一重要的是您是否正在使用OuterClass.this.method()例如

class OuterClass {
    void method() { }

    class InnerClass {
        void method() {
            OuterClass.this.method(); // not the same as method().
        }
    }
 }

回答by Tomasz Nurkiewicz

There is absolutely no difference between these constructs and the generated bytecode will be exactly the same, hence no performance impact. thisis resolved during compilation if not explicitly defined.

这些构造之间绝对没有区别,生成的字节码将完全相同,因此不会影响性能。this如果未明确定义,则在编译期间解析。

The only reason for using explicit thisis readability - some people find it easier to read because thissuggests that this is an instance method of current object.

使用显式的唯一原因this是可读性 - 有些人发现它更容易阅读,因为这this表明这是当前对象的实例方法。

Also please note that if method()is static, using thisis discouraged and misleading.

另请注意,如果method()是静态的,this则不鼓励和误导使用。

private static void method() {
}

private void foo() {
    this.method();    //generates warning in my IDE for a reason
}

And in this case it will also have no effect on performance.

在这种情况下,它也不会影响性能。

回答by David Tanzer

There is no real difference - At least there is no performance impact. I prefer not writing "this" - The IDE can usually highlight calls to this anyway, and I think it is less readable when every access to methods/fields/... start with "this.". But it really is a matter of personal preference.

没有真正的区别 - 至少没有性能影响。我不喜欢写“this”——无论如何,IDE 通常可以突出显示对 this 的调用,我认为当每次访问方法/字段/...以“this.”开头时,它的可读性会降低。但这确实是个人喜好的问题。

回答by duffymo

Using this.method() makes clear that a function associated with the instance of the class is being invoked, as opposed to a static function or one belonging to another object.

使用 this.method() 可以清楚地表明正在调用与类实例关联的函数,而不是静态函数或属于另一个对象的函数。

It's in the spirit of those C++ developers who like to prepend "m_" on all member variables in a class. It makes ownership unambiguous. I tend to like it, but it's not as important when you're using an IDE that clarifies such things using colors and fonts.

这符合那些喜欢在类中的所有成员变量上添加“m_”的 C++ 开发人员的精神。它使所有权明确。我倾向于喜欢它,但是当您使用使用颜色和字体来阐明此类内容的 IDE 时,这并不重要。

回答by Chris Knight

For methods there is no difference, but it can make a difference with fields. Consider this code:

对于方法没有区别,但它可以对字段产生影响。考虑这个代码:

private String someObject = "some value";

public String someMethod(String someObject) {
     //this.someObject refers to the field while
     //someObject refers to the parameter
}

回答by Atreys

That there is no difference can be seen by calling javap -c ClassNameon the commandline. For example:

通过调用javap -c ClassName命令行可以看出没有区别。例如:

public class This {
    private void method() {
    }
    public void noThis() {
        method();
    }
    public void useThis() {
        this.method();
    }
}

Produces the following disassembled output:

产生以下反汇编输出:

Compiled from "This.java"
public class This extends java.lang.Object{
public This();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public void noThis();
  Code:
   0:   aload_0
   1:   invokespecial   #2; //Method method:()V
   4:   return

public void useThis();
  Code:
   0:   aload_0
   1:   invokespecial   #2; //Method method:()V
   4:   return

}

回答by javanerd

There is no difference at all other than the readability. It makes it more clearer to the reader.

除了可读性之外,没有任何区别。它使读者更清楚。

回答by Phil

Have you tried to do this.variable in the constructor?

您是否尝试过在构造函数中执行 this.variable ?

In theory, in C++, since the object has not yet been created there is no this. I am not sure of the case in Java.

理论上,在 C++ 中,由于尚未创建对象,因此没有 this。我不确定 Java 中的情况。

回答by Developer Dude

Use this.method()and/or this.myVaror don't - on methods there is no difference, on vars there may be - but be consistent about it. I see it sprinkled throughout code, sometimes I even see this.m_myClassVar.

使用this.method()和/或this.myVar不使用 - 在方法上没有区别,在 vars 上可能有 - 但要保持一致。我看到它散布在整个代码中,有时我什至看到this.m_myClassVar.

Personally I prefer to prefix my class vars with a simple underscore and put a trailing underscore on my method args:

就我个人而言,我更喜欢在我的类 vars 前面加上一个简单的下划线,并在我的方法 args 上加上一个尾随下划线:

public MyClass
{
    private int _myInt;

    public void myMethod(final int myInt_, final int fooFactor_)
    {
        _myInt = myInt_ * fooFactor_;
    }
}

Although most IDEs will make it clear which is which, I find this tends to prevent misassignment and makes the intentions of the code clearer and IMO easier to read.

尽管大多数 IDE 会明确哪个是哪个,但我发现这有助于防止错误分配并使代码的意图更清晰,IMO 更易于阅读。

I do use _thisInstance.myMethod()(where _thisInstanceis a reference to the outer class) or _thisInstance._myVar, in inner classes/listeners/threads/etc. where I need to be clear about what method on which class I am calling and/or where I need to have a reference to a class instance.

我确实在内部类/侦听器/线程/等中使用_thisInstance.myMethod()(其中_thisInstance是对外部类的引用)或_thisInstance._myVar。我需要清楚我在哪个类上调用什么方法和/或我需要在何处引用类实例。