Why encapsulate attributes is for safety, for example
class SX {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const sx = new SX('哈哈',12);
sx.name = '刘'
The name attribute can be arbitrarily modified externally, which will lead to low security
Introduce an attribute
private 私有属性,只能在类内部进行访问修改,通过在类中添加方法使得私有属性可以被外部访问,之前我们不写,默认就是public
Then we write
class SX {
private _name: string;
private _age: number;
constructor(name: string, age: number) {
this._name = name;
this._age = age;
}
//定义方法,获取属性
getName(){
return this._name;
}
//定义方法,设置name属性
setName(value:string){
this._name = value
}
}
const sx = new SX('哈哈',12);
sx.setName('猪八戒')
Now the modification method is in my hands. If I don’t set the modification method, then this property will never be changed.
The above method is implemented by myself, TS provides a more convenient method
class SX {
private _name: string;
private _age: number;
constructor(name: string, age: number) {
this._name = name;
this._age = age;
}
//获取属性方法,get
get name(){
return this._name;
}
//设置属性方法,set
set name(value:string){
this._name = value;
}
}
const sx = new SX('哈哈',12);
sx.name; //获取
sx.name = '猪八戒'
In addition to public and private attributes, ts also has a protected attribute
protected 受保护的属性,只能在当前类和当前类的子类里面调用
How to use it?
class protect{
protected name : string;
constructor(name : string){
this.name = name;
}
}
class protectchildren extends protect{
getter(){
console.log(this.name) //可以取到
}
}
const aaa = new protectchildren('sss');
// aaa.name 取不到
Finally, I will introduce an easy way to write class
Written like this before
class bbbb{
public name : string;
constructor(name : string){
this.name = name;
}
}
Just write like this, the effect is the same
class bbbb{
constructor(public name:string){
}
}
Finally, to say it again, encapsulation is to make the attribute safer, and it can be modified by get and set.