Welcome to Qi-U Community for programmer and developer-Open, Learning and Share

Categories

0 votes
145 views
in Technique[技术] by (31.9m points)

typescript,如何在类中遍历所有实例化的对象?

有个叫animal的类,生成了 cat dog pig 三个实例对象。每个对象有一个布尔值的状态,比如就就status,status默认都是false。现在希望实现这样的功能,类的某个实例对象的状态变成true的时候,其他实例对象的状态都变成false。能不能在animal这个类里统一处理这个事情。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (31.9m points)
class animal {

private static instances: animal[] = [];

private static changeStatus(instance: animal) {

animal.instances.forEach((item: animal) => {

if (item !== instance) {

item.setStatus(false);

}

})

}

constructor(private status = false) {

animal.instances.push(this);

}

setStatus(status: boolean) {

this.status = status;

}

getStatus() {

return this.status;

}

enableStatus() {

this.setStatus(true);

animal.changeStatus(this);

}

}

const [cat, dog, pig] = [new animal(), new animal(), new animal()];

cat.enableStatus();

console.log(cat.getStatus(), dog.getStatus(), pig.getStatus());

dog.enableStatus();

console.log(cat.getStatus(), dog.getStatus(), pig.getStatus());

pig.enableStatus();

console.log(cat.getStatus(), dog.getStatus(), pig.getStatus());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
...