The prototype Keyword

The prototype keyword can save you a lot of memory. In the User class, every instance will contain the three properties and the method. Therefore, if you have 1,000 of these objects in memory, the method showUser will also be replicated 1,000 times. However, because the method is identical in every case, you can specify that new objects should refer to a single instance of the method instead of creating a copy of it. So, instead of using the following in a class constructor:

this.showUser = function()

you could replace it with this:

User.prototype.showUser = function()

Following Example shows what the new constructor would look like.

function User(forename, username, password)
this.forename = forename
this.username = username
this.password = password
User.prototype.showUser = function()
document.write("Forename: " + this.forename + "<br />")
document.write("Username: " + this.username + "<br />")
document.write("Password: " + this.password + "<br />")

You may also like...