Prototyping in JavaScript is one of the key concept that the language offers. It not only keeps the code clean, but also helps keeping a nominal memory usage. Let’s not play word games now, have a look at the code below.
1: var Team = function(runs,wickets){
2: this.Runs = runs;
3: this.Wickets = wickets;
4: }
Above is a simple JavaScript function/class Team with two properties, Runs and Wickets. We need to add a method, score in the function above which increments a Team’s Run count by 1. If we create that method inside the function Team itself, every object of the function ‘Team’ thus created, would have the copy of that method.
Consequently this would be the waste of memory, because we know that the method we are going to create would have to be same for every object of type Team, so why not just create a method somewhere once, and make every object to access that method from there. In this manner, we would have only one instance of the method defined in the memory, and all the object would use that method from that location rather then creating their own individually.
Declaring the method score as the prototype of the class Team, would solve our problem.
1: Team.prototype.score = function(){
2: this.Runs++;
3: };
We can now create as many instances of Team having no worries of the memory wastage.
1: var team1 = new Team(235,8);
2: var team2 = new Team(210,8);
3:
4: team2.score();
5:
6: console.log(team2.Runs);
We can call the prototyped method score just as we call the constructor methods, the interpreter would first scan the class for the existence of the method score, if not found, it will look for the defined prototypes.
Depending on what object is initiating the prototype’s method, the variable this would point to that object, thus incrementing the Runs of that particular instance of Team by 1.
Well this is not only for methods, but we can define properties as prototype of the function as well, like:
1: Team.prototype.Points = 10;
2:
3: console.log(team1.Points);
4: console.log(team2.Points);
Whose output would be like:
0 comments