面向对象 封装

封装:数据多权限和保密,在前端js里面用的不是很多,因为es6也好,es5也好,没有这种语法的特性,可以通过ts演示
封装首先要讲3个关键字
public 完全开放
protected 对子类开放
private 对自己开放
这三个关键字可以用于定义属性



// 父类,姓名,年龄可以公开,体重不能公开
class People {
    protected weight: any // 定义protected 属性
    constructor (public name:any, public age: any) {
        this.name = name
        this.age = age
        this.weight = 120
    }
    eat() {
        alert(`${this.name} eat something`)
    }
    speak() {
        alert(`my name is ${this.name}, age ${this.age}`)
    }
}

// 子类
class Student extends People {
    number
    private girlfriend // 定义private属性
    constructor(name, age, number) {
        super(name, age);
        this.number = number;
        this.girlfriend = 'xiaoli'
    }

    study() {
        alert(`${this.name} study`)
    }

    getWeight() {
        // 这个是在父类定义的,protected对自己,子类开放
        alert(`${this.weight} 斤`)
    }
}

// 实例
let xaioming = new Student('xiaoming', 10, 'A1');
xaioming.getWeight();
// girlfriend是私有的,不能调用
//xiaoming.girlfriend;
减少耦合,不该外露的不外露
利于数据,接口多权限管理
es6目前不支持,一般认为_开头多属性是private

猜你喜欢

转载自www.cnblogs.com/wzndkj/p/11706668.html