获取类的公共属性而不创建它的实例?

编程入门 行业动态 更新时间:2024-10-22 18:44:28
本文介绍了获取类的公共属性而不创建它的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我们有一个 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 语言服务获取这些,然后生成代码以协助运行时 (github/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 (github/Microsoft/TypeScript/wiki/Using-the-Language-Service-API).

这些都不是小事.

更多推荐

获取类的公共属性而不创建它的实例?

本文发布于:2023-11-14 00:07:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585670.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不   实例   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!