为什么在访问私有方法时使用它?

Why use this when accessing a private method?

我有一个关于 oop 的问题。这看起来可能真的微不足道。我在网上看到他们使用 this 访问私有方法的示例。真的有必要吗?它是特定于语言的吗?

这是一个示例,可以使用或不使用我们的 this

class A {
    def test(): String = {
        val x = this.test_2()
        x
    }

    private def test_2(): String = {
        "This is working"
    }
}

object Main extends App {
        val a = new A
        val x = a.test
        println(x)
    }

这里是没有 this 的相同代码。两者都在工作。

class A {
    def test(): String = {
        val x = test_2()
        x
    }

    private def test_2(): String = {
        "This is working"
    }
}

object Main extends App {
        val a = new A
        val x = a.test
        println(x)
    }

某些语言不接受使用没有 this 的方法,例如 python (self.),但在大多数情况下,这是一个可读性和安全性问题.

如果您在 class 之外定义一个与 class 的方法同名的函数,可能会导致问题。

通过添加 this,您知道它是来自 class 的方法。

"this"关键字指的是您当前正在其中编写代码的class。它主要用于区分方法参数和class字段。

例如,假设您有以下 class:

public class Student
{
string name = ""; //Field "name" in class Student

//Constructor of the Student class, takes the name of the Student
//as argument
public Student(string name)
{
   //Assign the value of the constructor argument "name" to the field "name"
   this.name = name; 
   //If you'd miss out the "this" here (name = name;) you would just assign the
   //constructor argument to itself and the field "name" of the
   //Person class would keep its value "".
}
}