This is the concept whereby an object inherits features from another object (which is the prototype). How does JavaScript do this? First it checks if the method exists on javascript and if it doesn't, it checks the _proto_ property. printType ( ) // undefined, because type does not exist Let's check that with the following code: This is the default function used when creating other objects. When creating objects using the constructor function of Obj, the constructor property of the prototype property was used. prototype also had two properties: constructor (which pointed back to the function) and _proto_. Remember above that hello had two properties: prototype and _proto_. With prototypes, you can create just one copy of printName and every object created from that prototype can have a different name value. What if php never uses its printName function, that would result in memory wastage especially when many other objects are created from this constructor function. We can see that while php and javascript have different name values, they have the same function code.
#What is prototype in javascript code#
The this variable used in Obj points to the object calling the function Obj (which in the above code is javascript and php). You can confirm that with this example:įunction Obj ( name ) At the declaration of every function, the JavaScript engine adds the prototype object property to that function which makes the function a prototype that other versions can be created from.
![what is prototype in javascript what is prototype in javascript](https://res.cloudinary.com/practicaldev/image/fetch/s--dzGHxVIl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://zellwk.com/images/2020/prototype/array-prototype.png)
![what is prototype in javascript what is prototype in javascript](https://cdn-images-1.medium.com/max/2400/1*TTEItJwXcPoOD9n8zlaIbg.png)
JavaScript works on the basis of prototypes. 'A' has four tyres, 'B' has four tyres and can fly, and 'C' has four tyres, cannot fly but can move in water. What this means is that, 'B' and 'C' are improved versions of 'A' but still contain features of 'A'. In most cases, 'A' would contain the most essential features that a vehicle should have while 'B' and 'C' would contain more features for other use cases. The prototype 'A' is the first version from which other versions like 'B' and 'C' are created. The concept of prototypesĪ prototype according to the dictionary is:Ī first or preliminary version of a device or vehicle from which other forms are developed.Ī graphical example to best explain this, is this vehicle example in the diagram below: hasOwnProperty ( "name" ) // trueīut animals does not have a method called hasOwnProperty so why aren't we having undefined? By the end of this article, we'll understand how this works and more.