What is a Prototype
- Apart from the primitive types, almost everything is an Object. A function is simply a callable object. Even the primitive types have Object versions. The Number Object is the object version of the number primitive type.
The second which is the more interesting one (in my opinion) is the use of constructors. (Please remove your OOP brains for now, this has nothing to do with class constructors). These constructors are functions which when called with the new keyword creates a new Object. The code inside the constructor is then executed to initialize some or all of the object properties by initializing them.
- Every constructor has a property called a prototype. This prototype is an Object which means you can set properties on it.
- Objects created from the same constructor also have a property called "prototype" which reference (simply point to) the prototype of the constructor. They all point to the same prototype meaning they all see and share the same constructor prototype. Continuing from our example above, it means they should all see the same value for height since height is on the constructor prototype.
As you can see from the result above, object1 and object2 have different names but they have the same height.
Calling the prototype property on the object2 gives undefined not because it does not exist but you are not suppose to access it directly (my opinion). But note that calling prototype on the constructor gives the prototype Object. This is deliberate and not an accident.
For Object prototype, a special accessor property called proto was introduced by browsers but is not included in the ECMAScript language spec. So please avoid using it in your code.
- Finally if you follow the prototype chain down until you get to the constructor prototype, this usually ends in the built-in type Object. This is where all the Object functions we use are like hasOwnProperty, toString, valueOf.
Top comments (0)