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
- It creates a function
Foo
which sets the name - It creates a function
myName
on the linked prototype Object of Foo. - 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. - 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.
- Now Bar's prototype object is having a function
myLabel
inside it. - 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 toBar's prototype
which in itself is linked toFoo'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.