如何查找使用Dojo声明创建的类的类型

How to find the type for a class created with Dojo declare?

本文关键字:声明 Dojo 创建 类型 何查找 查找      更新时间:2023-09-26

我正在Dojo中使用declare使用"class"定义创建一个对象。

我需要检查该对象的类型(类名)。

目前,我正在原型中使用属性declaredClass

declaredClass是检查类型的正确方法吗。Dojo中有更好的方法吗?

 define(["dojo/_base/declare", "my/Person"], function(declare, Person){
      return declare(Person, {
        constructor: function(name, age, residence, salary){
          // The "constructor" method is special: the parent class (Person)
          // constructor is called automatically before this one.
          this.salary = salary;
        },
        askForRaise: function(){
          return this.salary * 0.02;
        }
      });
    });

这取决于你要尝试做什么。如果你需要检查类是否是特定类型的,你可以使用以下方法:

myObject.isInstanceOf(Person);

例如:

require(["dojo/_base/declare"], function(declare) {
    var Mammal = declare(null, {
        constructor: function(name) {
            this.name = name;  
        },
        sayName: function() {
            console.log(this.name);
        }
    });
    var Dog = declare(Mammal, {
        makeNoise: function() {
            console.log("Waf waf");
        }
    });
    var myDog = new Dog("Pluto");
    myDog.sayName();
    myDog.makeNoise();
    console.log("Dog: " + myDog.isInstanceOf(Dog));
    console.log("Mammal: " + myDog.isInstanceOf(Mammal));
});

这将返回两次true,因为myDogDog的实例,也是Mammal的实例。