Software Development

JavaScript Static Properties and Methods

In JavaScript Object Creation and Object Methods and Properties, we talked about methods and properties that are tied to an object. Without an object, these properties are unusable and inaccessible to other codes. There is another type of members – static methods and properties. These are only accessible via the class itself. These are even inaccessible if referenced via objects.

[wp_ad_camp_5]

Non-static vs Static Members

So we have a Student class that has two (2) static members created as follows.

The static property classVersion represents current the version of the class; while the static function showClassDetails prints out the details of the class. Version and details not of objects. Static members are created as follows. Note that the class needs to be defined first before either of the statements.

[wp_ad_camp_4]

Using Non-static and Static Members

To use a public  non-static member:

To use a static member:

Using objects to access static Members

Static members are accessed only through the class. Accessing them via objects causes runtime error.

js-oop-20151031-1

[wp_ad_camp_3]

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like