如前所述,JavaScript 是一种基于原型继承的动态类型语言,因此您不能真正使用与类型语言相同的方法。你写的 JS 版本可能是:
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
}
然后,在您的应用中:
var obj = new Circle();
if (obj instanceof Shape) {
// do something with a shape object
}
或者,用鸭子打字:
if ("printSurface" in obj)
obj.printSurface();
// or
if (obj.printSurface)
obj.printSurface();
// or a more specific check
if (typeof obj.printSurface === "function")
obj.printSurface();
你也有Shape作为没有任何构造函数的对象,它更像是“抽象类”:
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
}
请注意,在这种情况下,您不能再使用 instanceof,因此,或者您回退到鸭式输入,或者您必须使用 isPrototypeOf,但仅在最近的浏览器中可用:
if (Shape.isPrototypeOf(obj)) {
// do something with obj
}
Object.create 在未实现 ES5 规范的浏览器中不可用,但您可以轻松使用 polyfill(请参阅链接)。