Psuedo-classical Inheritence in JavaScript
Yesterday I wrote about how to perform pseudo-classical inheritance and I wanted to follow up on that post with a few key distinctions. This is the example I gave of how to perform pseudo-classical inheritance:
function Fruit(sweetness, freshness, organic) { this.sweetness = sweetness; this.freshness = freshness; this.organic = organic; } function Apple(sweetness, freshness, organic) { Fruit.call(this, sweetness, freshness, organic); this.color = "red"; this.name = "apple"; } Apple.prototype = Object.create(Fruit.prototype); Apple.prototype.constructor = Apple
In this example it appears as though there are two distinct lines of code of
where inheritance is occurring. Lines Fruit.call(this, sweetness, freshness,
organic);
and Apple.prototype =
Object.create(Fruit.prototype);
. Both of these lines of code are involved
in pseudo-classical inheritance, but do you know what each one does?
Calling SuperClass Constructor
Fruit.call(this, sweetness, freshness, organic);
is actually has
no role in establishing a delegation relationship at all. This line does not
really have anything to do with inheritance per se. What this line really
does is call the the super classes constructor in the context of a child.
Conceptually it does
the same thing that super
does in Ruby or Python.
Establishing the Delegation Relationship
Apple.prototype = Object.create(Fruit.prototype);
is the line of
code solely responsible for establishing the prototypal chain. In my previous
article I was more focused on this relationship so I will not write about it
much here. I just wanted to take this time to focus on the distinction between
calling the super class constructor and establishing the delegation
relationship.