prototype Tutorial Add Object Methods and Properties to Class

Published :
Author :
Adam Khoury
The JavaScript prototype property allows us to add specialized methods and properties to our custom objects and classes. There may be occasions when you must specialize the functionality of an object in your application, and the prototype property allows us to do that. It also enables Object Inheritance in JavaScript, which we will be demonstrating in the video that follows this one. Before we discuss Object Inheritance let's write some code that demonstrates how the prototype property works at a basic level in JavaScript. <script> // Establish the Player class-based object function Player(){ this.name; this.hitpoints = 100; this.attack = function(opponent){ opponent.hitpoints -= 10; alert(this.name+" just hit "+opponent.name); } } // Create two new separate Player instances var p1 = new Player(); var p2 = new Player(); // Name the players p1.name = "Conan"; p2.name = "Hercules"; // Make player1 attack player2 p1.attack(p2); alert(p2.name+" has "+p2.hitpoints+" hit points left"); // Add a heal method to the Player object using the prototype property Player.prototype.heal = function(targetPlayer){ targetPlayer.hitpoints += 5; }; // Make player1 heal player2 p1.heal(p2); alert(p2.name+" has "+p2.hitpoints+" hit points left"); alert(p1.name+" has "+p1.hitpoints+" hit points left"); // Add an energy property to the Player object using the prototype property Player.prototype.energy = 200; alert(p1.energy); </script>