typescript类属性如何封装

发布时间:2022-10-25 14:00:52 作者:iii
来源:亿速云 阅读:135

本篇内容介绍了“typescript类属性如何封装”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

类属性的封装:通过属性的修饰符实现

属性的修饰符,如果是private,那么在类的外边通过getter 和 setter 方法 来存取属性;

1 class MyClass {
 2     public _name: string
 3     private _age: number
 4     
 5     constructor(){
 6         this._name="aa";
 7         this._age=12;
 8     }
 9     /**
10      * 读取属性
11      * ts中的getter方式
12      * @returns 
13      */
14     get age(){
15         return this._age;
16     }
17     /**
18      * 设置属性
19      * ts中的setter方式
20      * @param value 
21      */
22     set age(value:number){
23         this._age = value;
24     }
25

调用方式:

1 const aaa = new MyClass();
2 aaa._name="q";
3 console.log(aaa.age);//调用getter   12
4 aaa.age=2;//调用setter 
5 console.log(aaa);// {_name: 'q', _age: 2}

类的简略写法:

1 class C{
2     constructor(public name:string,public age:number){
3        
4     }
5

等同于:

1 class C{
2     name:string;
3     age:number;
4     constructor(name:string,age:number){
5         this.age =age;
6         this.name=name;
7     }
8

“typescript类属性如何封装”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. TypeScript(一)TypeScript培养类型思维
  2. TypeScript笔记

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

typescript

上一篇:Java中Unable to execute 'doFinal' with cipher instance报错怎么解决

下一篇:typescript接口如何定义

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》