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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function Student() { // Non-static member, requires an instance of Student. var _name; // Non-static member, requires an instance of a Student to reference it outside of the class. this.getName = function() { return _name }; // Non-static member, requires an instance of a Student to reference it outside of the class. this.setName = function(v) { _name = v; }; }; // Static member - property, does not need an instance of Student for other codes to reference it. Student.classVersion = '1.0'; // Static member - method, does not need an instance of Student for other codes to reference it. Student.showClassDetails = function() { console.log('Version: ' + Student.classVersion); console.log('Created By: Turreta.com'); console.log('Created On: July 14, 2015 9:00 AM'); }; |
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]
1 2 3 4 5 | [class-name].[property-name] = [any-value]; [class-name].[method-name] = function() { // Method implementation }; |
Using Non-static and Static Members
To use a public non-static member:
1 2 3 | var studentObj = new Student(); studentObj.setName('Picasso'); console.log(studentObj.getName()) |
To use a static member:
1 2 | console.log(Student.classVersion); Student.showClassDetails(); |
Using objects to access static Members
Static members are accessed only through the class. Accessing them via objects causes runtime error.
1 2 | console.log(studentObj.classVersion); studentObj.showClassDetails(); |
[wp_ad_camp_3]