JavaScript Prototype Cheat Sheet

JavaScript Prototype Cheat Sheet

A Cheat Sheet For Beginners

Description

Prototypes in JavaScript are a lot like classes in Ruby. All JavaScript object inheret properties and methods from their parent prototypes. The prototype itself is also an object, but the syntax for adding to the prototype object is not the same as the syntax of adding to a regular object. An object called Object() inherets properties from Object.prototype.

Creating A Prototype

The standard way to create a new prototype in JavaScript is by using the object constructor function as displayed below:

Input Output
function student(first, last, school, age){
  this.firstName = first;
  this.lastName = last;
  this.school = school;
  this.age = age;
}

var student1 = new student("Jane", "Doe", "DBC", 24)              
                                
 
    >> console.log(student1)
    => { firstName: 'Jane', 
      lastName: 'Doe', 
      school: 'DBC', 
      age: 24 } 
    
                                

Modifying the Prototype

Modifying the prototype can be done in two ways. The first is through the manual insertion of a new property or method into the object constructor. The second way is by using the .prototype method by typing in: prototype_name.prototype.new_property = "default_property_value." An example of this method is included below:

Input Output
function student(first, last, school, age){
  this.firstName = first;
  this.lastName = last;
  this.school = school;
  this.age = age;
}

var student1 = new student("Jane", "Doe", "DBC", 24)
                                    
student.prototype.gender = "female";

                                
 
    >> console.log(student1.gender)
    => female   
                                
Input Output
function student(first, last, school, age){
  this.firstName = first;
  this.lastName = last;
  this.school = school;
  this.age = age;
}

var student1 = new student("Jane", "Doe", "DBC", 24)

student.prototype.summary = function() 
       {return this.firstName + " " 
        + this.lastName + " is attending " 
        + this.school + ".";}
                                
 
    >> console.log(student1.summary())
    => Jane Doe is attending DBC.