class Person2 {
constructor(private _name : string){};
get name() {
return this._name;
};
set name(name: string) {
this._name = name;
}
}
const per = new Person2('lyb');
console.log(per.name);
per.name = 'yj';
console.log(per.name);
// 单例模式
class Single {
private static instance: Single; // 把instance属性挂载到Single类上 ,用来存储实例
private constructor(public name: string) {}
/**
* 创建实例
* static: 把这个方法挂载到类上,而不是实例上
*/
static getInstance() {
if (!this.instance) this.instance = new Single('lyb');
return this.instance
}
}
const single1 = Single.getInstance();
const single2 = Single.getInstance();
console.log(single1.name); // lyb
console.log(single2.name); // lyb
// readonly修饰符
class Person3 {
public readonly name: string; // 只读,不能改
constructor(name: string){
this.name = name;
}
}
const person3 = new Person3('lyb')
person3.name = 'yj' // 报错
console.log(person3.name);
// 抽象类
abstract class Geom {
width: number;
// 抽象方法
abstract getArea(): number;
}
// 继承抽象类后必须实现里边的抽象方法
class Circle extends Geom {
getArea() {
return 1;
}
}
// ==================
// 复习 接口使用
interface Person4 {
name: string;
}
interface Teacher4 extends Person4 {
teacherAge: number;
}
interface Student4 extends Person4 {
age: number;
}
interface Driver {
name: string;
age: number;
}
const teacher4 = {
name: 'lyb',
teacherAge: 18
}
const student4 = {
name: 'yj',
age: 18
}
const getUserInfo = (user: Person4) => {
console.log(user.name);
}
getUserInfo(teacher4)
【TypeScript class中的getter跟setter】
最新推荐文章于 2024-11-01 23:18:04 发布