- 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
this
is 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
prototype
object field here. We will be analysing the behaviour of literally setting theprototype
property 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 theprototype
is 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
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
Native prototypes [TODO]
Prototype methods, objects without proto [TODO]
Content Updates
- 2023-09-09 - init