top | item 22428270

(no title)

jimmyspice | 6 years ago

Prototypical inheritance is not something I really understand in too much detail (and maybe I was late to the game, since I've never really felt I missed anything). Now js has 'classes' which I think are sugar over proto, can't remember.

You can think of a prototype as 'cloning' an object (but not quite), distinct from classes in OOP, which are typically created afresh, i.e. no entanglement occurs between instance 1 and 2 of the same class (unless of course explicitly specified in a constructor). If I have `var a = {one: 1, two: 2}`, I can use that as a 'live template' to stamp out other 'instances' that prototypically inherit from that ancestor. Any attribute lookups that are not specified directly on an object created with a prototype recursively look up the prototype ancestry chain until it is found. So if c -> b -> a (where a -> b means a prototypically inherits from b), looking up a property on c will try to look for the property on c first, failing that b, then a. If nothing is found, `undefined` is returned.

Let's open our inspector and have a play: ``` var a = {one: 1, two: 2}; var b = Object.create(a); // create b, based on prototype a var c = Object.create(b);

console.log(c.one) // 1, how, when this wasn't even defined! We looked up the p. chain until we found it

b.three = 3;

console.log(a.three) // undefined, a's only prototype is Object console.log(c.three) // 3, wow, c knew about something that happened to b! This is different from OOP. 'instances' share data defined at runtime.

```

discuss

order

No comments yet.