Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: how to access static properties

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 ?

like image 385
Jeanluca Scaljeri Avatar asked May 02 '13 18:05

Jeanluca Scaljeri


People also ask

Where can static properties be accessed?

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.

What are static properties JavaScript?

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.

Can I use static in JavaScript?

Static class methods are defined on the class itself. You cannot call a static method on an object, only on an object class.

How do you call a static method?

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.


1 Answers

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.

like image 91
Bergi Avatar answered Sep 22 '22 22:09

Bergi