获取类的公共属性而不创建它的实例? [英] Get the public properties of a class without creating an instance of it?

查看:54
本文介绍了获取类的公共属性而不创建它的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个 JavaScript 类:

Let's imagine that we have a 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;
})();

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

I want to iterate its methods and properties. I have no problem with the methods.

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

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

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

My problem comes when I want to iterate its properties:

  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.我想将此代码用作框架的一部分,这样我就无法控制其他开发人员定义的类.我想避免创建实例的需要,因为如果构造函数有某种验证,例如:

The only way that I have found is to create an instance and use Object.getOwnPropertyNames. I want to use this code as part of a framework so I will not have control over the classes defined by other developers. I want to avoid the need of creating an instance because if the constructor had some sort of validation like:

function Person(name, surname) {

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

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

我将无法使用上面的代码.您知道是否可以在不创建类的实例的情况下获取类的公共属性?

I wouldn't be able to use the code above. Do you know if it is possible to get the public properties of a class without creating an instance of it?

推荐答案

您知道是否可以在不创建类的实例的情况下获取类的公共属性?

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

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

If you are talking about runtime them no, not without ugly hacks like toString (which gives you a string representation of the function body).

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

However you can get these at compile time using the TypeScript language service and then do code generation to assist the runtime (https://github.com/Microsoft/TypeScript/wiki/Using-the-Language-Service-API).

这些都不是小事.

这篇关于获取类的公共属性而不创建它的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆