代码之家  ›  专栏  ›  技术社区  ›  maroodb

我们可以获得javascript类的属性吗?

  •  0
  • maroodb  · 技术社区  · 6 年前

    我有一个javascript类:

    class UserDTO {
    
       constructor(props) {
           this.username = props.username;
           this.birthday = props.birthday;
       }
      }
    

        class Utils  {
    
              convertEntityToDTO (entityObj, DTOClass) {
                  // entityObj is an instance of a Entity,
                  // DTOClass is a class not an instance
                   let objDTO = new DTOClass();
                   Object.getOwnPropertyNames(entityObj)
                        .filter(prop => DTOClass.hasOwnProperty(prop))
                        .forEach(prop => {
                            objDTO[prop] = entityObj[prop];
                        });
        }
    }
    

    这在课堂上不起作用;拥有自己的财产,只与对象一起工作;是验证属性是否为类属性的一种方法吗?或者我必须创建一个要测试的实例?

    1 回复  |  直到 6 年前
        1
  •  0
  •   quirimmo    6 年前

    你可以用 hasOwnProperty getOwnPropertyNames :

    class A {
      constructor() {
        this.ex = 'TEST';
      }
    }
    
    var a = new A();
    console.log(a.hasOwnProperty('ex'));
    console.log(Object.getOwnPropertyNames(a));

    class B {
      constructor() {}
      
      exMethod() {
        console.log('test');
      }
    }
    
    var b = new B();
    console.log(Object.getPrototypeOf(b).hasOwnProperty('exMethod'));
    console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(b)));