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.