// 示例代码:一个简单的 JavaScript 接口示例
// 定义一个接口,使用类来模拟接口的行为
class IShape {
// 定义接口方法
draw() {
throw new Error("This method should be overridden.");
}
}
// 实现接口的类
class Circle extends IShape {
constructor(radius) {
super();
this.radius = radius;
}
// 重写接口方法
draw() {
console.log(`Drawing a circle with radius ${this.radius}`);
}
}
class Rectangle extends IShape {
constructor(width, height) {
super();
this.width = width;
this.height = height;
}
// 重写接口方法
draw() {
console.log(`Drawing a rectangle with width ${this.width} and height ${this.height}`);
}
}
// 使用接口
const shapes = [new Circle(5), new Rectangle(10, 20)];
shapes.forEach(shape => {
shape.draw(); // 调用接口方法
});
IShape
类定义了一个 draw
方法,该方法在子类中必须被重写。如果直接调用 IShape
的 draw
方法,会抛出错误,提示需要重写该方法。Circle
和 Rectangle
类分别实现了 IShape
接口,并重写了 draw
方法,以实现具体的功能。shapes
数组,调用每个形状对象的 draw
方法,展示不同形状的绘制逻辑。如果你对这个示例有任何疑问或需要进一步的帮助,请告诉我!
上一篇:js 混淆
下一篇:js 切割字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站