MegaRacer MegaRacer - 8 months ago 40
Javascript Question

Prototypes and usage Javascript

I have a chunk of code below:

function Foo(name){ = name;

Foo.prototype.myName = function() {

function Bar(name, label){, name);
this.label = label;

Bar.prototype = Object.create(Foo.prototype);

Bar.prototype.myLabel = function(){
return this.label;

var a = new Bar("a" , "obj a");


Okay, now as per my understanding

  1. It creates a function
    which sets the name

  2. It creates a function
    on the linked prototype Object of Foo.

  3. It creates a function
    which just sets the label and uses the function Foo's functionality to set the name instead of doing it itself.

  4. Then the prototype linkage is established between Foo and Bar. So I assume that there are two separate prototype objects linked to one another for Foo and Bar respectively.

  5. Now Bar's prototype object is having a function
    inside it.

  6. The call to new Bar creates a new object
    and links it's prototype object to Bar's prototype.

So takeways are :

  • Foo's prototype contains one get function -

  • Foo itself just sets a property- name

  • Bar's prototype is having one get function -

  • Bar itself is just setting a property - mylabel

  • The object
    prototype is linked to
    Bar's prototype
    which in itself is linked to
    Foo's prototype
    . So in total there are three prototype objects.

Is this flow of thinking correct ? Please rectify or add something to enlighten the discussion. I am fairly new to the language and it's nuances and hardly the use cases/practical examples of prototype.


Firstly to enumerate Foo.prototype:

Foo.prototype = { constructor: Foo, myName: function() { return}};

Then Bar calls Foo to apply 'name' to the the instance of Bar being constructed, rather than doing it itself, before setting its second parameter as a new Bar object property.

But Bar.prototype is set to {} protypically inheriting from Foo.prototype. So for example, Bar.prototype.constructor == Foo; // true

Bar.prototype is assigned a local own property method myLabel, inheritable by Bar objects but not by Foo objects.

So points 1,2,3 are correct.

Point 4 is incorrect. There is a prototypical inheritance established such that Bar.prototype inherits from Foo.prototype. It is not mutual and is a one way inheritance: JavaScript does not support any kind of bi-directional prototypical inheritance.

Points 5 and 6 are correct.