DEV Community

Kaziu
Kaziu

Posted on ā€¢ Edited on

1 1

šŸ¤” For what prototype??

what is prototype?

simply put, special property in object

For example

function Worker(name, age) {
  this.name = name
  this.age = age
}

// ā­ prototype !!
Worker.prototype.msg = function() {
  console.log('I am ' + this.name)
}

const maria = new Worker('Maria', 20)
const kaziu = new Worker('Kaziu', 27)
const jhon = new Worker('Jhon', 37)

maria.msg() // I am Maria
kaziu.msg() // I am Kaziu
jhon.msg() // I am Jhon 
Enter fullscreen mode Exit fullscreen mode

ā–¼ But we could write like that

function Worker(name, age) {
  this.name = name
  this.age = age
  // ā­ like this ####################
  this.msg = function() {
    console.log('I am ' + this.name)
  }
  // ###########################
}

const maria = new Worker('Maria', 20)
const kaziu = new Worker('Kaziu', 27)
const jhon = new Worker('Jhon', 37)

maria.msg() // I am Maria
kaziu.msg() // I am Kaziu
jhon.msg() // I am Jhon
Enter fullscreen mode Exit fullscreen mode

šŸ¤” So for what we use prototype ??
šŸ˜Ž One of the reason is memory management

Image description

If you don't use prototype, each instance would create new function on new memory preference when each time instance is created

Image description

Otherwise function doesn't create each time when instance is created as you see in image.
Each instance just look for preference of prototype (= instances look for memory place of prototype function)

ref. from this course

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadogā€™s testing tunnel.

Download The Guide