【问题标题】:Why use this when accessing a private method?为什么在访问私有方法时使用它?
【发布时间】:2015-04-22 09:31:50
【问题描述】:

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

这是一个可以使用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)
    }

【问题讨论】:

    标签: oop methods this private private-methods


    【解决方案1】:

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

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

    通过添加this,您知道它是类中的方法。

    【讨论】:

      【解决方案2】:

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

      例如,假设您有以下类:

      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 "".
      }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-05-16
        • 2023-03-14
        • 1970-01-01
        • 2021-05-18
        • 2015-04-09
        • 1970-01-01
        • 1970-01-01
        • 2011-06-10
        • 1970-01-01
        相关资源
        最近更新 更多