如何获得Javascript类字段和函数

How to get Javascript class fields and functions

本文关键字:函数 字段 何获得 Javascript      更新时间:2023-09-26

有没有办法从JavaScript类中获得函数和字段,而不初始化该类的对象?

var SimpleClass = function() {
    this.type = 'singleClassType';
    this.getType = function() {
        var self = this;
        return self.type;
    }
}

我想获得类型字段(类似于静态)。

我可以这样做,但是我真的不想使用prototype of class:

SimpleClass.prototype.type = 'customName'
下面是我使用的代码:
var Class1 = function(id) {
    this.id = id;
}
Class1.prototype.type = 'class1';
var Class2 = function(id) {
    this.id = id;
}
Class2.prototype.type = 'class2';
var Class3 = function(id) {
    this.id = id;
}
Class3.prototype.type = 'class3';
var Class4 = function(id) {
    this.id = id;
}
Class4.prototype.type = 'class4';
var xml = {},
xmlText = '';
$(document).ready(function(){
    generateObjects();
});
function generateObjects() {
    for(var i=1;i<5;i++){
        if(typeof eval('Class'+i).prototype.getHtml === 'undefined'){
            $.ajax({
                dataType: 'xml',
                url: 'file.xml',
                async: false,
                success: function(data){
                    xmlText = data;
                    addClassData();
                }
            });
            function addClassData(){
                xml['"'+eval('Class'+i).prototype.type+'"'] = xmlText;
            }
            eval('Class'+i).prototype.getHtml = function(){
                var self = this;
                return xml['"'+self.type+'"'];
            }
        }
        var kl =  eval('Class'+i),
            obj = new kl(i);
        console.log(obj.getHtml());
    }
}

有没有办法从JavaScript类中获得函数和字段,而不初始化该类的对象?

。除非你反编译函数,否则解析JS代码并查找属性赋值。

我可以这样做,但是我真的不想使用prototype of class:

如果这个字段应该在类的所有实例中共享,那么使用原型并没有什么问题。

如果你说的"静态"是指它是类成员而不是实例成员,那么你也可以直接在构造函数中添加属性:

var SimpleClass = function() {
    this.getType = function() {
        return SimpleClass.type;
        // alternatively, something like `this.constructor.type`
        // but only if you understand when this works and when not
    }
}
SimpleClass.type = 'singleClassType';

像这样访问属性/字段:

var SimpleClass = function(){
    this.type = 'singleClassType';
    this.getType = function(){
        var self = this;
        return self.type;
    }
}
SimpleClass["type"] = 'customName';
alert(SimpleClass["type"]);

也可以。看看这篇MDN文章-属性访问器。

请阅读这篇MDN文章-使用对象以获得关于使用JavaScript的OOP概念的更全面的信息,以避免@PaulS在他的评论中指出的问题。