封装首先要讲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