ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
### [`this`关键字](http://www.kotlincn.net/docs/reference/this-expressions.html) [TOC] `this`关键字持有当前对象的引用。我们可以使用`this`来引用变量或者成员函数,也可以使用`return this`,来返回某个类的引用。 代码示例 ~~~ fun main(args: Array<String>) { val demo = ThisDemo() println(demo.whatIsThis()) } class ThisDemo { val thisis = "THIS IS" fun whatIsThis(): ThisDemo { println(this.thisis) //引用变量 this.howIsThis()// 引用成员函数 return this // 返回此类的引用 } fun howIsThis(){ println("HOW IS THIS ?") } } ~~~ 运行结果 ``` THIS IS HOW IS THIS ? A基础.ThisDemo@5e481248 ``` ### This 表达式 为了表示当前的接收者我们使用this表达式: * 在[类](http://www.kotlincn.net/docs/reference/classes.html#继承)的成员中,this指的是该类的当前对象。 * 在[扩展函数](http://www.kotlincn.net/docs/reference/extensions.html)或者[带有接收者的函数字面值](http://www.kotlincn.net/docs/reference/lambdas.html#带有接收者的函数字面值)中,this表示在点左侧传递的接收者参数。 ~~~ fun main(args: Array<String>) { //在扩展函数或者带接收者的函数字面值中, this 表示在点左侧传递的接收者参数。 val sum= fun Int.(x:Int):Int = this +x println("sum: ${sum}") println("1.sum(1):${1.sum(1)}") val concat =fun String.(x:Any) = this + x val str="abc" println("str:${str}") println("str.concat(123):${str.concat(123)}") println("str.concat(true):${str.concat(true)}") } ~~~ 运行结果 ``` sum: kotlin.Int.(kotlin.Int) -> kotlin.Int 1.sum(1):2 str:abc str.concat(123):abc123 str.concat(true):abctrue Process finished with exit code 0 ``` 如果this没有限定符,它指的是最内层的包含它的作用域。要引用其他作用域中的this,请使用标签限定符: ### 限定的this 要访问来自外部作用域的this(一个[类](http://www.kotlincn.net/docs/reference/classes.html)或者[扩展函数](http://www.kotlincn.net/docs/reference/extensions.html), 或者带标签的[带有接收者的函数字面值](http://www.kotlincn.net/docs/reference/lambdas.html#带有接收者的函数字面值))我们使用`this@label`,其中`@label`是一个代指this来源的标签: ``` class A { // 隐式标签 @A inner class B { // 隐式标签 @B fun Int.foo() { // 隐式标签 @foo val a = this@A // A 的 this val b = this@B // B 的 this val c = this // foo() 的接收者,一个 Int val c1 = this@foo // foo() 的接收者,一个 Int val funLit = lambda@ fun String.() { val d = this // funLit 的接收者 } val funLit2 = { s: String -> // foo() 的接收者,因为它包含的 lambda 表达式 // 没有任何接收者 val d1 = this } } } } ```