I want to access a static property using an instance. Something like this
function User(){
console.log('Constructor: property1=' + this.constructor.property1) ;
}
User.prototype = {
test: function() {
console.log('test: property1=' + this.constructor.property1) ;
}
}
User.property1 = 10 ; // STATIC PROPERTY
var inst = new User() ;
inst.test() ;
Here is the same code in a jsfiddle
In my situation I don't know which class the instance belongs to, so I tried to access the static property using the instance 'constructor' property, without success :( Is this possible ?
Static properties are accessed using the Scope Resolution Operator ( :: ) and cannot be accessed through the object operator ( -> ). It's possible to reference the class using a variable.
Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.
Static class methods are defined on the class itself. You cannot call a static method on an object, only on an object class.
A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.
so I tried to access the static property using the instance 'constructor' property
That's the problem, your instances don't have a constructor
property - you've overwritten the whole .prototype
object and its default properties. Instead, use
User.prototype.test = function() {
console.log('test: property1=' + this.constructor.property1) ;
};
And you also might just use User.property1
instead of the detour via this.constructor
. Also you can't ensure that all instances on which you might want to call this method will have their constructor
property pointing to User
- so better access it directly and explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With