Reputation: 680
I have created a class(constructor) in java-script as given below which has a property of type static.
function MyClass(property1 )
{
this.Property1 = property1 || "";
}
MyClass.StaticProperty = {
Running: "Running",
NotRunning: "NotRunning"
}
Now I can access the above static property using constructor name as below:
MyClass.StaticProperty.Running
But I also want to access the property using an instance of the constructor as below:
var myClassInstance = new MyClass("value");
var status = myClassInstance.StaticProperty.Running;
I am aware that I can access if it is a prototype variable or variable defined inside the constructor. But I don't want to do that because I want it to behave as a static variable.
Use case:
I am having multiple constructors with the same property name. I am getting these constructor instances in the array. I want to loop through each constructor in an array and read the static variable. For example
var allStaticPropertyValues = [];
for(index = 0; index < arrayOfConstructors.length; index++)
{
for(var property in arrayOfConstructors[index].StaticProperty)
{
allStaticPropertyValues.push(arrayOfConstructors[index].StaticProperty[property]);
}
}
What I tried:
I tried to get class Type using typeof keyword but it is giving only as an object, not constructor reference that I can use to access the property.
instanceOfObject.constructor.getname() which will give the name of the constructor as a string and not as a reference.
Upvotes: 1
Views: 1326
Reputation: 36564
You can use constructor
property of instance of the MyClass
to get MyClass
and then you can access the static variables of MyClass
function MyClass(property1 )
{
this.Property1 = property1 || "";
}
MyClass.StaticProperty = {
Running: "Running",
NotRunning: "NotRunning"
}
var myClassInstance = new MyClass("value");
var status = myClassInstance.constructor.StaticProperty.Running;
console.log(status)
Upvotes: 2
Reputation: 370679
Accessing the constructor
property will give you a direct reference to the constructor (the object, not as a string), so you can then just access its StaticProperty
property:
function MyClass(property1 ){
this.Property1 = property1 || "";
}
MyClass.StaticProperty = {
Running: "Running",
NotRunning: "NotRunning"
}
var myClassInstance = new MyClass("value");
var status = myClassInstance.constructor.StaticProperty.Running;
console.log(status);
Upvotes: 1