- Published on
Object Prototype
4 mins
- Authors
- Name
- Juleshwar Babu
Table Of Contents
- Prototypal inheritance
- F.prototype
- Native prototypes [TODO]
- Prototype methods, objects without proto [TODO]
- Content Updates
Source Link: https://javascript.info/prototypes
Prototypal inheritance
Prototypal inheritance is JS’ way of allowing an object to extend or inherit behaviour from another object.
[[Prototype]]is a hidden internal object field which is used to enable this.If a field doesn’t exist on an object, the JS engine follows the prototype chain to search for the field.
let animal = { eats: true, walk() { alert("Animal walk"); } }; let rabbit = { jumps: true, __proto__: animal }; let longEar = { earLength: 10, __proto__: rabbit }; // walk is taken from the prototype chain longEar.walk(); // Animal walk alert(longEar.jumps); // true (from rabbit)
There is another field
__proto__which exists for historical reasons. It is a historical getter/setter for[[Prototype]]. Modern JS way of getting/setting prototype is by usingObject.getPrototypeOf(obj) / Object.setPrototypeOf(objA, objB)In a method call, the value of
thisis always decided by the object behind the .(dot)… even if a method is found in the prototype chainlet animal = { run() { this.isRunning = true } } let elephant = { __proto__: animal } elephant.run(); elephant.isRunning // true animal.isRunning // undefined
F.prototype
We will be talking about the
prototypeobject field here. We will be analysing the behaviour of literally setting theprototypeproperty to a function.Setting Animal.prototype = animal literally states, when a new object is created using
new Animal, set its[[Prototype]]property to theanimal. The"prototype"property only has such a special effect when set on a constructor function, and invoked withnew. On regular objects theprototypeis nothing special.let animal = { eats: true }; function Rabbit(name) { this.name = name; } Rabbit.prototype = animal; let rabbit = new Rabbit("White Rabbit"); // rabbit.__proto__ == animal alert( rabbit.eats ); // true![Image shows when the prototype property of functionB is set to objectA, any new instance created using new functionB will have its [[prototype]] set to objectA](/_next/image?url=%2Fstatic%2Fimages%2Fblog%2Fjavascript.info-notes%2Fobject-prototype%2Fprototype-property-relation.png&w=1920&q=75)
Every function has a default prototype assigned to it
function Test() {} // Test.prototype = { constructor: Test } Test.prototype.constructor === Test // true let testChild = new Test() testChild.prototype === Test.prototype testChild.constructor === Test![Image shows how prototype, constructor and [[prototype]] are related](/_next/image?url=%2Fstatic%2Fimages%2Fblog%2Fjavascript.info-notes%2Fobject-prototype%2Fprototype-constructor-instance-relation.png&w=1920&q=75)
Native prototypes [TODO]
Prototype methods, objects without proto [TODO]
Content Updates
- 2023-09-09 - init