Welcome!
Everything is fine.
Appendix: OOP Inheritance with the Old Syntax
Defining the superclass is just the same as defining an ordinary class, which is good. We won't necessarily know in advance that someone wants to subclass it.
The Superclass¶
function Shape(color) {
this.color = color;
}
Shape.prototype.getColor =
function () { return this.color; };
Shape.prototype.setColor =
function (color) { this.color = color; };
Shape.prototype.toString = function() {
return "[A "+this.color+" "
+this.constructor.name+"]";
};
var s1 = new Shape("red");
console.log("s1 is "+s1.toString());
// [A red Shape]
Note that constructor.name
is built-in and gives the name of the
constructor as a string, so in this case it produces the string
Shape
. Thus the string returned by s1.toString()
is [A red Shape]
The Subclass¶
Obviously, the subclass must be aware of the superclass. In particular,
any initialization that the superclass needs to do has to be done by the
constructor of the subclass. So, the subclass needs to call the
superclass constructor while supplying the value of this
. Usually,
constructors are magically given a value of this
because they are
invoked with the new
keyword in front, but that doesn't happen with the
subclass. So, we use the call
method.
function Rectangle(color,c1,c2) {
// initialize using superclass
Shape.call(this,color);
...
}
Rectangle.prototype =
Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
The call
method¶
Finally, we have a non-trivial use of the call
method: we need to invoke
(call) the Shape constructor, but we also need to specify an existing
object (rather than new
) as the value of this
Prototype Activity¶
Let's build a picture of what's going on with prototypes, constructors, methods and such from shapes.html
Let's look at the trouble with the Triangle
object in that reading.
t1.__proto__;
t1.toString();
t1 instanceof Shape;
t1.constructor;
Step 1. Set the prototype
:
Triangle.prototype = Object.create(Shape.prototype);
t2 = new Triangle("gold", p1, p2, p3);
and repeat those operations on t1
and t2
Step 2. Fix the constructor:
Triangle.prototype.constructor = Triangle;
and repeat the operations.