A JavaScript prototype is used to add new properties and methods to an existing object constructor.
An object constructor is made in JavaScript as follows:
function Player(firstName, lastName, team, position) {this.firstName = firstName;this.lastName = lastName;this.team = team;this.position = position;}
The object can then be assigned values as follows:
var player1 = new Player("Diego", "Maradona", "Argentina", "Forward");var player2 = new Player("Alan", "Shearer", "England", "Forward");
Now, if you wanted to add a new property to the Player
object, JavaScript’s prototype property will be needed. This way, the property added will be shared among all instances of the object.
All JavaScript objects inherit properties and methods from a prototype:
Date
objects inherit from Date.prototype
.Array
objects inherit from Array.prototype
.Player
objects (from the example above) inherit from Player.prototype
.The Object.prototype
is on top of the prototype inheritance chain; Date
objects, Array
objects, and Player
objects all inherit from Object.prototype
.
The following code snippet highlights the syntax needed to use prototypes to add a new “sport” property to the Player
object:
function Player(firstName, lastName, team, position) {this.firstName = firstName;this.lastName = lastName;this.team = team;this.position = position;}var player1 = new Player("Diego", "Maradona", "Argentina", "Forward");Player.prototype.sport = "Football";console.log(player1.lastName + " was good at " + player1.sport);
New methods can also be added to the object constructor using prototype
, as shown below:
function Player(firstName, lastName, team, position) {this.firstName = firstName;this.lastName = lastName;this.team = team;this.position = position;}var player1 = new Player("Diego", "Maradona", "Argentina", "Forward");Player.prototype.showName = function() {return this.firstName + " " + this.lastName;};console.log(player1.showName());