What is prototype
property, and why is it necessary? So far, I have learnt that this provides public access to more intrinsic, and private prototype
In JavaScript, function objects have a built-in .prototype
property. The value of this property is an object. If the function is used as a constructor, the resulting instances inherit from that "prototype" object.
Example:
var Dog = function () {}; // the constructor function
Dog.prototype.bark = function () {}; // adding a method to Dog.prototype
var dog1 = new Dog; // creating a new instance
dog1.bark(); // the instance inherits the "bark" method from Dog.prototype
Note that the .prototype
property (of function objects) is not the same as the [[Prototype]]
internal property. All objects contain the latter. It's an internal reference to an object's prototype. (In the above example, the dog1
object's [[Prototype]]
refers to Dog.prototype
.) On the other hand, only function objects have a built-in .prototype
property (which makes sense since only function objects can be used as constructors).