获取 class 的 public 属性而不创建它的实例?

Get the public properties of a class without creating an instance of it?

假设我们有一个 JavaScript class:

var Person = (function () {
    function Person(name, surname) {
        this.name = name;
        this.surname = surname;
    }
    Person.prototype.saySomething = function (something) {
        return this.name + " " + this.surname + " says: " + something;
    };
    return Person;
})();

我想迭代它的方法和属性。我对这些方法没有问题。

  var proto = Person.prototype,
      methods = Object.keys(proto);

  // iterate class methods ["saySomething"]
  for (var i = 0; i < methods.length; i++) {
    // do something...
  }

当我想迭代它的属性时,我的问题来了:

  var proto = Person.prototype,
      targetInstance = new Person(), // this is my problem!
      properties = Object.getOwnPropertyNames(targetInstance),

  // iterate class properties ["name", "surname"]
  for (var i = 0; i < properties.length; i++) {
    // do something...
  }

我找到的唯一方法是创建实例 并使用Object.getOwnPropertyNames。我想将这段代码用作框架的一部分,这样我就无法控制其他开发人员定义的 classes。我想避免创建实例的需要,因为如果构造函数具有某种验证,例如:

function Person(name, surname) {

  if(typeof name === "undefined" || typeof surname === "undefined"){ 
    throw new Error() 
  }

  this.name = name;
  this.surname = surname;
}

我无法使用上面的代码。您知道是否可以在不创建 class 实例的情况下获取 public 属性吗?

在对象构造它们之前,属性不存在。 如果您的 class 看起来像:

var Person = (function () {
    Person.prototype.name = null;    
    Person.prototype.surname = null;
    function Person(name, surname) {
        this.name = name;
        this.surname = surname;
    }
    Person.prototype.saySomething = function (something) {
        return this.name + " " + this.surname + " says: " + something;
    };
    return Person;
})();

你也会看到名字和姓氏,但当然你不能指望看起来像那样的对象。

Do you know if it is possible to get the public properties of a class without creating an instance of it?

如果你在谈论 runtime 他们不,不是没有像 toString 这样的丑陋黑客(它给你一个 string 函数体的表示) .

不过,您可以使用 TypeScript 语言服务在编译时获取这些内容,然后进行代码生成以协助运行时 (https://github.com/Microsoft/TypeScript/wiki/Using-the-Language-Service-API)。

这些都不是微不足道的。