Dart - this关键字

Dart - this关键字 首页 / Dart入门教程 / Dart - this关键字

this关键字用于引用当前的类对象。它指示类,方法或构造函数的当前实例。它也可以用来调用当前的类方法或构造函数。它消除了类属性和参数名称相同之间的不确定性。如果我们声明类属性与参数名称相同,则这种情况将在程序中造成歧义,那么this关键字可以通过在类属性前添加前缀来消除歧义。可以将其作为参数传递给类方法或构造函数。

让我们了解以下有关this关键字如何工作的示例。

示例 - 1不使用this关键字

class Mobile {  
    String modelname;  
    int man_year;  
      
     // 创建构造函数 
    Mobile(modelname, man_year){  
             modelname = modelname;  
             man_year = 2020;  
             print("Mobile's model name is: ${modelname}, and the manufacture year is: ${man_year}");  
    }  
                                                              }  
    void main(){  
	Mobile mob = new Mobile("iPhone 11 ",2020);  
    }
}       

输出

Mobile's model name is: iPhone 11 , and the manufacture year is: 2020

示例 - 2使用this关键字

class Mobile {
    String modelname;
    int man_year;
    
    //Creating constructor
    Mobile(modelname, man_year){
       this.modelname = modelname;
       this.man_year = 2020;
       print("Mobile's model name is: ${modelname}, and the manufacture year is: ${man_year}");
    }
                                                              }
    void main(){
        Mobile mob = new Mobile("IPhone 11",2020);}
     }

输出

Mobile's model name is: IPhone 11, and the manufacture year is: 2020

上面的例子与前一个程序相同,但是this关键字的唯一差异。

this.modelname = modelname;
this.man_year = 2020;

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

TensorFlow快速入门与实战 -〔彭靖田〕

从0开发一款iOS App -〔朱德权〕

零基础学Java -〔臧萌〕

即时消息技术剖析与实战 -〔袁武林〕

HarmonyOS快速入门与实战 -〔QCon+案例研习社〕

云计算的必修小课 -〔吕蕴偲〕

快速上手C++数据结构与算法 -〔王健伟〕

手把手带你写一个MiniSpring -〔郭屹〕

AI绘画核心技术与实战 -〔南柯〕

好记忆不如烂笔头。留下您的足迹吧 :)