0

I was learning prototypes in JS and if you look at the code below

function Car(){
this.brand="BMW";
}

Car.prototype.drive = function(){
console.log(brand);
}

the question is WHY to declare Car.prototype.drive outside of the function? INSTEAD OF INSIDE THE FUNCTION? The second question is it is suggested not to use since "_proto__" was deprecated but WHY?

1 Answers1

0

JavaScript engine implicitly adds a prototype property to the function Car. Try console.dir(Car) and you can see prototype property being attached to this function.

This prototype is actually an object (called as prototype object), where you can add properties and methods to a function. In your sample code, you are adding a drive method to your function Car.

So, the answer to your question is, since prototype object is not part of the actualy function code, but an object attached as property to the Car function, you need to write it outside the function.

Note: The ES6 version of writing your sample code would be:

class Car() {
  this.brand = "BMW";
  drive () {
    console.log('brand`);
  }
}

This class pattern is just syntactical sugar over JavaScript's existing prototype-based inheritance. It is recommended to use this pattern over prototype based pattern.

Answer to your second question: __proto__ is deprecated in favor of Object.getPrototypeOf / Object.setPrototypeOf. It is recommended to not use it since it's a slow operation and can mess things up. read more on this here.

makkBit
  • 373
  • 2
  • 14