静态属性、Setter和Getter以及单例模式的实现
Setter和Getter
class Person {
constructor(private _name: string) {}
get name() {
return this._name + " lee";
}
set name(name: string) {
const realName = name.split(" ")[0];
this._name = realName;
}
}
测试及结果
- 测试代码:
const person = new Person("dell");
console.log(person.name);
person.name = "dell lee";
console.log(person.name);
- 结果:
- 分析:
根据代码,我们可以发现在类的 name 方法前面加上了get
和set
这两个关键字,当直接打印 person.name 的时候,就会调用 get name 方法,输出dell lee
,然后,对 person.name 进行赋值操作,就会调用 set name 方法,经过处理之后,输出结果依然是dell lee
。
类中的静态属性
- 非常直观,就是在属性前面加上
static
关键字,这样子该属性就可以通过 类名.属性名的方式进行访问了,不需要通过new
的方式创建实例,然后通过实例去访问这些属性。
class Demo {
private static instance: Demo;
private constructor(public name: string) {}
static getInstance() {
}
}
单例模式的实现
class Demo {
private static instance: Demo;
private constructor(public name: string) {}
static getInstance() {
if (!this.instance) {
this.instance = new Demo("dell lee");
}
return this.instance;
}
}
测试及结果
- 测试代码:
const demo1 = Demo.getInstance();
const demo2 = Demo.getInstance();
console.log(demo1.name);
console.log(demo2.name);
console.log(demo1 === demo2);
- 结果:
当然啦,大家如果有补充的或者其它问题,欢迎大家在评论区交流啊,路漫漫其修远兮,吾将上下而求索,希望大家可以一起坚持下去啊!😎😎😎~~~
如果这篇文章能够帮助到您,希望您不要吝惜点赞👍👍和收藏💖💖,您的支持是我继续创作的动力 💪💪!!!