Prototypes in JavaScript
Do you remember the prototype chain?
Here is the summary of JavaScript's prototypes from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain.
- In JS, there is no implementation of a
class
per se- the ES2015's
class
keyword is just a syntactical sugar
- the ES2015's
- When it comes to inheritance, JS only has one construct: objects.
- An object has
- private
prototype
: a link to another object - own properties: other properties
- private
- An object
a
's prototype is denoted asa.[[Prototype]]
- You can access the
prototype
of an objecta
(a.k.a.a.[[Prototype]]
)byObject.getPrototypeOf(a)
Object.setPrototypeOf(a)
- Note that
func.prototype
is a different beast!- It specifies the
[[Prototype]]
to be assigned to all instances of objects created by the given function when used as a constructor.
- It specifies the
f.prototype.b = 3;
f.prototype.c = 4;
Object.getPrototypeOf(Object.getPrototypeOf(o)).d = 5
Object.setPrototypeOf(Object.getPrototypeOf(o), {e:6})