Search code examples
javascriptmethodsprototype

why to use prototypes over methods


I was watching tutorial about functions. And there is an example

function Car(){
this.running = false
}
Car.prototype.start = function(){
    this.running = true
}
Car.prototype.stop = function(){
    this.running = false
}

var c = new Car()
c.running // false
c.start // true
c.running // true

but there is another way of doing the same thing

function Car(){
    this.running = false;
    this.start = function(){
        this.running = true
    }
    this.stop = function(){
        this.running = false
    }
}

var c = new Car()
c.running // false
c.start // true
c.running // true

Question:

  1. what is pros and cons of using prototypes compared to methods?
  2. when should we avoid/use prototypes?
  3. when should we avoid/use methods?

Solution

  • Ideally, whenever you want to share properties among multiple instances of a type, you make use of the prototype. In your first example

    function Car() {
      this.running = false
    }
    Car.prototype.start = function() {
      this.running = true
    }
    Car.prototype.stop = function() {
      this.running = false
    }
    
    var c = new Car()
    var d = new Car()
    var e = new Car()
    console.log(c.__proto__ === d.__proto__) //true
    c.running // false
    c.start // true
    c.running // true
    

    Here prototype object will remain same for c, d and e, Hence you are saving runtime memory consumption as you are reusing same functions for all the three, but with different context.

    In your second example

    function Car(){
        this.running = false;
        this.start = function(){
            this.running = true
        }
        this.stop = function(){
            this.running = false
        }
    }
    
    var c = new Car() // check comparing  c.__proto__ ===  d.__proto__
    var d =  new Car()
    var e = new Car()
    c.running // false
    c.start // true
    c.running // 
    

    Here c, d, e will have their own copy of function, Consuming more memory!! Ideally, one should think about reusability while designing such objects. prototype way seems to better and performant than method way.