Reputation: 1
Is there any way to get functions and fields from JavaScript class without initializing an object of that class?
var SimpleClass = function() {
this.type = 'singleClassType';
this.getType = function() {
var self = this;
return self.type;
}
}
I want to get type field (which is like static).
I can do something like this, but I really don`t want to use prototype of class:
SimpleClass.prototype.type = 'customName'
Here is the code I use:
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());
}
}
Upvotes: 0
Views: 6862
Reputation: 665448
Is there any way to get functions and fields from JavaScript class without initializing an object of that class?
No. Unless you decompile the function, parse the JS code and look for property assignments.
I can do something like this, but I really don't want to use prototype of class:
There's nothing wrong with using the prototype if this field is supposed to be shared amongst all instances of the class.
If by "static" you mean that it's rather a class member than an instance member, you can put properties directly on the constructor as well:
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';
Upvotes: 3
Reputation: 7830
Accessing the property/field like this:
var SimpleClass = function(){
this.type = 'singleClassType';
this.getType = function(){
var self = this;
return self.type;
}
}
SimpleClass["type"] = 'customName';
alert(SimpleClass["type"]);
should work too. Have a look at this MDN article - property accessors.
Have a look at this MDN article - Working with objects for more thorough information about OOP concepts using JavaScript in order to avoid the problem that @PaulS pointed out in his comment.
Upvotes: 1