1

I don't entirely understand how this works:

function inherit(C,P) {
  var F = function () {};
  F.prototype = P.prototype;
  C.prototype = new F();
}

function Parent(){};
Parent.prototype.species = "human";
function Child(){};
inherit(Child, Parent);
var kid = new Child();
Parent.prototype.talk = function () {return "Hello there!"};

How does the kid object have the talk function? Doesn't the inherit function only give the Child "class" the prototype of the parent at the time you call the inherit function? How is it able to update it?

thgaskell
  • 12,772
  • 5
  • 32
  • 38
mike
  • 43
  • 3
  • 1
    http://javascript.crockford.com/prototypal.html – Krzysztof Safjanowski Nov 09 '14 at 00:06
  • That like looks a lot like the polyfil for Object.create. More info on prototype and constructor functions here: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 if you want to do it correctly I'd advice you not to follow Crockford's documentation on it. – HMR Nov 09 '14 at 01:15

2 Answers2

2

The inherit function does this:

function inherit(C, P) {
  var F = function () {};    // Defines a new constructor function.
  F.prototype = P.prototype; // Sets `F.prototype` to *be an alias* of `P.prototype`
  C.prototype = new F();     // Sets `C.prototype` to *be an instance* of `F`
}

If you change C by Child, P by Parent and F by anonymous class. It will render something like this:

Child.prototype is an instance of anonymous class, which shares the same prototype as Parent.

This makes this statement to be true: Child.prototype.__proto__ === Parent.prototype.

So, any changes you make to Parent.prototype will be seen by the instance of the anonymous class in Child.prototype. And, consequently, this makes it acessible to Child instances too.

But, the inverse is not true! For example, if you add properties to Child.prototype, you are only changing the instance of the anonymous class and it will not be visible to instances of Parent.

Thiago Negri
  • 5,221
  • 2
  • 28
  • 39
1

The basic principle here is that in Javascript when you set one object to equal another, you are only creating a reference to the original object and not a duplicate of that object. Therefore any changes to the original object will also apply to the link you created.

Here's a simpler version that follows the same principle:

var parent = {
    "speak": "hello"
}

var child = parent;
parent.shout = "HELLO!"

alert(child.shout); // Will popup 'HELLO!'

So when you're setting your Child.prototype to equal Parent.prototype, Child.prototype is now just a reference to the Parent.prototype object, so any changes you make to either will apply to both.

Jordan Burnett
  • 1,799
  • 8
  • 11