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
▼ 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
🤔 So for what we use prototype ??
😎 One of the reason is memory management
If you don't use prototype, each instance would create new function on new memory preference when each time instance is created
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
Top comments (0)