As said, JavaScript is a dynamic typed language based on prototypal inheritance, so you can’t really use the same approach of typed languages. A JS version of what you wrote, could be:
function Shape(){
throw new Error("Abstract class")
}
Shape.prototype.printSurface = function () {
throw new Error ("Not implemented");
}
function Rect() {
// constructor;
}
Rect.prototype = Object.create(Shape.prototype);
Rect.prototype.printSurface = function() {
// Rect implementation
}
function Circle() {
// constructor;
}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.printSurface = function() {
// Circle implementation
}
Then, in your app:
var obj = new Circle();
if (obj instanceof Shape) {
// do something with a shape object
}
Or, with duck typing:
if ("printSurface" in obj)
obj.printSurface();
// or
if (obj.printSurface)
obj.printSurface();
// or a more specific check
if (typeof obj.printSurface === "function")
obj.printSurface();
You cold also have Shape
as object without any constructor, that it’s more “abstract class” like:
var Shape = {
printSurface : function () {
throw new Error ("Not implemented");
}
}
function Rect() {
// constructor;
}
Rect.prototype = Object.create(Shape);
Rect.prototype.printSurface = function() {
// Rect implementation
}
function Circle() {
// constructor;
}
Circle.prototype = Object.create(Shape);
Circle.prototype.printSurface = function() {
// Circle implementation
}
Notice that in this case, you can’t use instanceof
anymore, so or you fallback to duck typing or you have to use isPrototypeOf
, but is available only in recent browsers:
if (Shape.isPrototypeOf(obj)) {
// do something with obj
}
Object.create is not available in browser that doesn’t implement ES5 specs, but you can easily use a polyfill (see the link).