TypeScript系列学习笔记-OOP思想之类的封装

使用TS实现类的封装,关键字:class (类似C#语言),语法:

1.使用 class 关键字声明;

2.使用 constructor 关键字声明构造函数;

3.使用 private 关键字声明私有成员(或属性);

4.可以使用 get/set 来实现私有成员访问器;

5.支持 static 静态字段或方法;

实例代码如下,首先声明一个Person 类:

//typescript:类 class
class Person {
    //构造函数(方法)
    constructor(name: string, sex: string) {
        this._Name = name;
        this._Sex = sex;
    }

    //属性:姓名
    private _Name: string;
    get Name() {
        return this.Name;
    }
    set Name(name: string) {
        this._Name = name;
    }

    //属性:性别
    private _Sex: string;
    get Sex() {
        return this.Sex;
    }
    set Sex(sex:string) {
        this._Sex = sex;
    }

    //静态函数(方法)
    static SayHi(person:Person) {
        return "大家好好,我是:" + person.Name;
    }
}

Person类的调用:

//调用
var myPerson = new Person("张三", "男");
alert(Person.SyaHi(myPerson)); //类名调用静态函数(方法SayHi)

TS和JS对比:


补充:类中成员修饰符,公有public、私有private 、受保护的protected 与 只读的 readonly 。

扫描二维码关注公众号,回复: 1130112 查看本文章

public :公有类型,类似 C# 语言,TS中成员默认 public ,而 C# 中必须明确使用 public 指定成员是公有的;

private:私有类型,当成员被标记成 private时,它就不能在声明它的类的外部访问,只有该类(本类)中可以访问;

protected : 受保护类型,protected修饰符与 private修饰符的行为很相似,但有一点不同, protected成员在派生类中仍然可以访问;

readonly : 只读类型,使用 readonly关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化;

猜你喜欢

转载自blog.csdn.net/chaitsimplelove/article/details/79834979
今日推荐