类
继承
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
class Student extends Person {
constructor(name: string) {
super(name)
}
}
const s=new Student('123');
console.log(s.name);
class Person {
name: string = '133'
}
class Student extends Person {
getName() {
return this.name;
}
}
let s = new Student();
console.log(s.getName());
只读属性
- 只读属性可以在构造器中赋值,但是赋值之后就不可以被修改了
class Person{
readonly name:string;
constructor(name:string){
this.name=name;
}
}
const p =new Person('why');
console.log(p.name);
- 属性本身不能被修改,但是如果他是对象类型时,对象中不是可读的属性是可以进行修改的
class Person {
readonly name: string;
readonly friend: Person;
age: number
constructor(name: string, age: number, friend?: Person) {
this.name = name;
this.age = age;
this.friend = friend;
}
}
const p = new Person('wxy', 23, new Person('ccc', 45));
p.friend.age=90
console.log(p.friend);
访问器
//私有属性
class Person {
private _name: string;
constructor(name: string) {
this._name = name
}
//访问器的setter和getter
set name(newName) {
this._name = newName
}
get name() {
return this._name;
}
}
const p=new Person('xx');
p.name='kdl'
console.log(p.name);
//tsc 编译的时候指定高一点的版本要不然访问器会报错 Tsc 2.ts -t es5
参考学习 ts https://blog.csdn.net/weixin_42215167/article/details/117756434