Yet another key concept in JavaScript is the class properties or in Object Oriented terminology, the static properties. Alike of the prototypes, these properties do not initializes in memory when every time an object is created, rather they are created only once, when the function/class is defined. Moreover, these properties since being class properties and hence cannot be accessed via objects, instead they can only be accessed via using dot operator after the function/class name for which they are defined.
Using the same example in the previous post, we have the following class:
1: var Team = function(runs,wickets){
2: this.Runs = runs;
3: this.Wickets = wickets;
4: }
Now instead of adding the method score as prototype, let’s add it as class property which can be done as:
1: Team.score = function(arg){
2: arg.Runs++;
3: }
If you are going to use this.Runs++, and since being the class property and not the object property, the method will try to search for the property Runs in it’s own scope, but since there is no such property define, it won’t do anything. Therefore, we need to pass in the instance of the object for which we want to increment the value of Runs. Which can be done as:
1: var team1 = new Team(200,3);
2: var team2 = new Team(200,3);
3:
4: Team.score(team2);
5: console.log("Team 1 Runs: " + team1.Runs);
6: console.log("Team 2 Runs: " + team2.Runs);
In general, the static properties holds the data which does not depends upon the content of any instance. However in our case, the output would be:
0 comments