DEV Community

mz4
mz4

Posted on

JavaScript - Prototype

Every function in JavaScript has a prototype property..
Prototype is a property that allows us to share methods across all instances of a function.
When we create a new instance of an object, we inherit all properties and methods of that object.

Turns out that this:

class Animal {
  constructor(name, energy) {
    this.name = name
    this.energy = energy
  }
  eat(amount) {
    this.energy += amount
  }
  sleep(length) {
    this.energy += length
  }
  play(length) {
    this.energy -= length
  }
}

const leo = new Animal('Leo', 7)
const snoop = new Animal('Snoop', 10)
Enter fullscreen mode Exit fullscreen mode

is syntactic sugar for this:

function Animal (name, energy) {
  this.name = name
  this.energy = energy
}

Animal.prototype.eat = function (amount) {
  this.energy += amount
}

Animal.prototype.sleep = function (length) {
  this.energy += length
}

Animal.prototype.play = function (length) {
  this.energy -= length
}

const leo = new Animal('Leo', 7)
const snoop = new Animal('Snoop', 10)
Enter fullscreen mode Exit fullscreen mode

And if we want to list all methods of an Array for example, we just have to do:

console.log(Array.prototype);

Top comments (0)