public
- TS可以在属性前添加属性的修饰符
- public修饰的属性可以在任意位置访问(修改) 默认值
(function () {
class Person {
name: string;
public age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const per = new Person("yrq", 18);
per.name = "lyq";
per.age = -38;
console.log(per);
})();
private
- private 私有属性,私有属性只能在类内部进行访问(修改)
- 通过在类中添加方法使得私有属性可以被外部访问
js使用getter和setter的方法:
(function () {
class Person {
private name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
getName() {
return this.name;
}
setName(value: string) {
this.name = value;
}
getAge() {
return this.age;
}
setAge(value: number) {
if (value >= 0) this.age = value;
}
}
const per = new Person("yrq", 18);
per.setName("lyq");
per.setAge(33);
console.log(per.getName(), per.getAge());
})();
TS中get和set语法糖:
(function () {
class Person {
private _name: string;
private _age: number;
constructor(name: string, age: number) {
this._name = name;
this._age = age;
}
get name() {
return this._name;
}
set name(value: string) {
this._name = value;
}
get age() {
return this._age;
}
set age(value: number) {
if (value >= 0) this._age = value;
}
}
const per = new Person("yrq", 18);
per.name = "lyq";
per.age = 33;
console.log(per);
})();
protected
- protected 受包含的属性,只能在当前类和当前类的子类中访问(修改)
(function () {
class A {
protected num: number;
constructor(num: number) {
this.num = num;
}
}
class B extends A {
test() {
console.log(this.num);
}
}
const b = new B(123);
})();
简写方法:
(function () {
class C {
constructor(public name: string, public age: number) {}
}
const c = new C("yrq", 11)
console.log(c);
})();