如何在JavaScript中测试类实例的存在

问题描述

我有这个:

class Animal {
    constructor() {
        Animate();

        function Animate() {
            if (true) { // What do change here for the object to self-check if it still exists?
                console.log('1');
                requestAnimationFrame(Animate);
            }
        }
    }
}

var dog = new Animal();

setTimeout(function () {
    dog = undefined;
    // The Animate() should no longer be called at this point.
},3000);

如果类的实例不再“存在”,我该如何修改 Animate()函数以停止再次调用自身??


感谢您的所有回复。就像下面已经说过的那样,似乎我需要实现某种“销毁”方法来处理和管理Animal类的实例的Animate()函数调用。并不是我真正想要的,我希望实例能够自我感知并知道何时不再需要它。

不确定这是否有助于澄清以下一些问题,但我们可以:

var dog1 = new Animal();
var dog2 = new Animal();
var dog3 = new Animal();

每个实例将运行自己的Animate()。如果实例设置为未定义(例如,也可以设置为null),则不应再调用Animate()调用。这里的目标是使对象实例具有自我意识,不再需要它。创建destroy方法将意味着我们在外部进行调用,因此该实例不是自觉的。

如果使用jQuery,则可以在类内添加$(this)(0).length来检测对象是否仍然存在。

解决方法

在您的情况下,我只会使用:

  if (dog) {
    requestAnimationFrame(Animate);
  }

dogundefined时,这是“虚假”。

,

我同意布拉德的解决方案,但是作为对原始问题的解答,您可以使用instanceof关键字来测试某事物是另一个类的实例。

对于您引用的代码:


if (dog instanceof Animal) {
    console.log('1');
    requestAnimationFrame(Animate);
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...