09属性的封装
封装¶
-
对象实质上就是属性和方法的容器,它的主要作用就是存储属性和方法,这就是所谓的封装
-
默认情况下,对象的属性是可以任意的修改的,为了确保数据的安全性,在TS中可以对属性的权限进行设置
-
只读属性(readonly):
-
如果在声明属性时添加一个readonly,则属性便成了只读属性无法修改
-
TS中属性具有三种修饰符:
-
public(默认值),可以在类、子类和对象中修改
- protected ,可以在类、子类中修改
-
private ,可以在类中修改
-
示例:
-
public
-
```typescript class Person{ public name: string; // 写或什么都不写都是public public age: number;
constructor(name: string, age: number){ this.name = name; // 可以在类中修改 this.age = age; }
sayHello(){ console.log(
大家好,我是${this.name}
); } }
class Employee extends Person{ constructor(name: string, age: number){ super(name, age); this.name = name; //子类中可以修改 } }
const p = new Person('孙悟空', 18); p.name = '猪八戒';// 可以通过对象修改 ```
-
-
protected
-
```typescript class Person{ protected name: string; protected age: number;
constructor(name: string, age: number){ this.name = name; // 可以修改 this.age = age; }
sayHello(){ console.log(
大家好,我是${this.name}
); } }
class Employee extends Person{
Text Onlyconstructor(name: string, age: number){ super(name, age); this.name = name; //子类中可以修改 }
}
const p = new Person('孙悟空', 18); p.name = '猪八戒';// 不能修改 ```
-
-
private
-
```typescript class Person{ private name: string; private age: number;
constructor(name: string, age: number){ this.name = name; // 可以修改 this.age = age; }
sayHello(){ console.log(
大家好,我是${this.name}
); } }
class Employee extends Person{
Text Onlyconstructor(name: string, age: number){ super(name, age); this.name = name; //子类中不能修改 }
}
const p = new Person('孙悟空', 18); p.name = '猪八戒';// 不能修改 ```
-
## 属性存取器
-
对于一些不希望被任意修改的属性,可以将其设置为private
-
直接将其设置为private将导致无法再通过对象修改其中的属性
-
我们可以在类中定义一组读取、设置属性的方法,这种对属性读取或设置的属性被称为属性的存取器
-
读取属性的方法叫做setter方法,设置属性的方法叫做getter方法
-
示例:
-
```typescript class Person{ private _name: string;
constructor(name: string){ this._name = name; }
get name(){ return this._name; }
set name(name: string){ this._name = name; }
}
const p1 = new Person('孙悟空'); console.log(p1.name); // 通过getter读取name属性 p1.name = '猪八戒'; // 通过setter修改name属性 ```
-