Javascript 6 – prototype property

In my earlier post I used the prototype property to give all my cookies a method to scare away the Cookie Monster. It worked well but I started questioning what this prototype thing really refers to.

So I asked my true friend, the console.​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 😉

1. I set up the constructor and created one cookie

 function MyCookie(flavor) {
 this.flavor = flavor;
 }
 var chocolateChipCookie = new MyCookie('Chocolate chip');
 console.log(chocolateChipCookie instanceof MyCookie);
 // making sure the cookie is an instance of MyCookie

2. I inspected the created cookie.

 console.dir(chocolateChipCookie);

  • it has the flavor property
  • it has __proto__ property. It points to an Object where my chocolate chip cookie inherits from. It says who his daddy or mommy is. And this is tricky, it doesn’t point right to the MyCookie constructor but to the MyCookie constructor prototype.

3. I inspected the constructor prototype

 console.dir(MyCookie.prototype);

  • It is an Object, once again only a special one.
  • Its __proto__  is the raw JS object.
  • It has a constructor property which points to the function MyCookie, the constructor

4. I checked my new theory that chocolateChipCookie’s parent is actually the constructor’s prototype property.

And it shows that my chocolateChipCookie inherits from the constructor’s prototype.

[code lang=”javascript”]
console.log(chocolateChipCookie.__proto__ === MyCookie.prototype);
//logs true
[/code]

So what this all really means?

  • prototype is a special property that only functions have
  • it points to a special Object that becomes a parent to all new instances
  • when the new instance of a constructor is created, the instance property __proto__ is set to the constructor’s prototype

So when I write this

[code lang=”javascript”]
MyCookie.prototype.newMethod = function() {}
console.dir(MyCookie.prototype);
[/code]

I am giving a new method to the parent object of all my cookies.
And as they know where to inherit from via the __proto__ property they will look for this method at their parent and find it.

..And I had a feeling that the prototype is the constructor
And I had a feeling it points to itself somehow somehow somehow…