Skip to content

Instantly share code, notes, and snippets.

@ninadvadujkar
Last active July 7, 2020 13:56
Show Gist options
  • Save ninadvadujkar/bf1da934438a1b731b04a96ee3872b57 to your computer and use it in GitHub Desktop.
Save ninadvadujkar/bf1da934438a1b731b04a96ee3872b57 to your computer and use it in GitHub Desktop.
What is [[Prototype]]?
Every object has a special hidden property called [[Prototype]] which is used to access that object's prototype.
prototype object <- [[Prototype]] <- object
[[Prototype]] is hidden and internal
__proto__ can be used to set [[Prototype]]
Fun fact:
1. __proto__ is a historical getter/setter for [[Prototype]]
2. Object.getPrototypeOf/Object.setPrototypeOf also get/set the prototype
3. __proto__ can be either an object or null
E.g.
let animal = {
eats: true
};
let rabbit = {
jumps: true
};
rabbit.__proto__ = animal;
// we can find both properties in rabbit now:
alert( rabbit.eats ); // true
alert( rabbit.jumps ); // true
E.g. with new F()
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
Setting Rabbit.prototype = animal
literally states the following: "When a new Rabbit is created, assign its [[Prototype]] to animal".
const obj = {};
obj.__proto === Object.prototype // true
Modern alternatives to __proto
const newObj = Object.create(proto[, descriptors]) // where "proto" is the [[Prototype]] of the newObj. Basically similar to const newObj = {}; newObj__proto = proto;
const newObj = Object.getPrototypeOf(obj)
const newObj = Object.setPrototypeOf(obj, proto)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment