class People {
private name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
setName(name: string) {
this.name = name;
}
getName() {
return this.name;
}
setAge(age: number) {
this.age = age;
}
getAge() {
return this.age;
}
}
const p = new People("zhangsan", 18);
p.setAge(20);
console.log(p.getAge());
这样封装,都要调用setXXX()
或getXXX()
方法。
为了方便,提供了一种简便的封装。但是这种方法,<font style="color:#DF2A3F;">set</font>``<font style="color:#DF2A3F;">get</font>
后面的方法名不能与属性名相同。
class People {
private _name: string;
constructor(name: string) {
this.name = name;
}
set name(name: string) {
console.log("set name");
this._name = name;
}
get name() {
console.log("get name");
return this._name;
}
}
const p = new People("zhangsan");
p.name = "lisi";
console.log(p.name);