No Prototype vs Prototype

Methods in JavaScript can be added in the constructor or through the prototype. In the following table these approaches are compared side by side:

No Prototype Prototype
Properties are defined with var Properties are defined with this
Properties are referenced as variableName Properties are referenced as this.variableName
Methods are defined inside the constructor Methods are defined outside the constructor
Methods are defined without the prototype Methods are defined with the prototype
Example Definition

function Example() {
  var property = "No prototype.";
  this.getProperty = function() {
    return property;
  };
}
Example Definition

function Example() {
  this.property = "Prototype.";
}

Example.prototype.getProperty = function() {
  return this.property;
};
Example Usage (identical)

var example = new Example();
console.log(example.getProperty());
// prints "No prototype."
Example Usage (identical)

var example = new Example();
console.log(example.getProperty());
// prints "Prototype."
Inefficient because methods are not shared Efficient because methods are shared

Video

Here is a video that converts a no-prototype queue implementation into a prototype one:

2 comments on “No Prototype vs Prototype”

Leave A Reply

Your email address will not be published.