MegaRacer MegaRacer - 6 months ago 21
Javascript Question

Prototypes and usage Javascript

I have a chunk of code below:

function Foo(name){
this.name = name;
}

Foo.prototype.myName = function() {
return this.name;
}

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

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

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

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

a.myName();
a.myLabel();


Okay, now as per my understanding


  1. It creates a function
    Foo
    which sets the name

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

  3. It creates a function
    Bar
    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
    myLabel
    inside it.

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



So takeways are :


  • Foo's prototype contains one get function -
    myName

  • Foo itself just sets a property- name

  • Bar's prototype is having one get function -
    myLabel

  • Bar itself is just setting a property - mylabel

  • The object
    a's
    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.

Answer

Firstly to enumerate Foo.prototype:

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

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.