当前位置:首页 > JavaScript

js 多态实现

2026-02-01 00:58:56JavaScript

多态的概念

多态是面向对象编程的核心特性之一,指同一操作作用于不同对象时产生不同行为。JavaScript 通过原型链和对象动态特性实现多态。

基于原型链的多态实现

通过原型继承实现方法重写,子类覆盖父类方法:

function Animal() {}
Animal.prototype.sound = function() {
  console.log('Animal makes sound');
};

function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.sound = function() {
  console.log('Bark!');
};

const animal = new Animal();
const dog = new Dog();

animal.sound(); // Animal makes sound
dog.sound();    // Bark!

基于class语法的多态

ES6 class语法通过extends和super实现更清晰的多态:

class Shape {
  draw() {
    console.log('Drawing shape');
  }
}

class Circle extends Shape {
  draw() {
    console.log('Drawing circle');
  }
}

const shape = new Shape();
const circle = new Circle();

shape.draw(); // Drawing shape
circle.draw(); // Drawing circle

鸭子类型实现多态

JavaScript作为动态类型语言,通过"鸭子类型"实现多态,只关注对象行为而非类型:

function makeSound(animal) {
  if (animal && typeof animal.sound === 'function') {
    animal.sound();
  }
}

const cat = {
  sound: () => console.log('Meow')
};

const car = {
  sound: () => console.log('Vroom')
};

makeSound(cat); // Meow
makeSound(car); // Vroom

参数多态实现

通过函数参数不同实现不同行为:

function calculateArea(shape, ...args) {
  if (shape === 'circle') {
    return Math.PI * args[0]  2;
  } else if (shape === 'rectangle') {
    return args[0] * args[1];
  }
}

console.log(calculateArea('circle', 5)); // 78.53981633974483
console.log(calculateArea('rectangle', 4, 5)); // 20

多态应用建议

  1. 优先使用class语法实现继承多态,代码结构更清晰
  2. 接口多态适合需要灵活扩展的场景
  3. 避免过度使用鸭子类型,适当增加类型检查保证可靠性
  4. 复杂多态场景可考虑使用TypeScript增强类型安全

js 多态实现

标签: 多态js
分享给朋友:

相关文章

js实现轮播

js实现轮播

实现轮播图的基本思路 轮播图的核心逻辑是通过定时切换展示的图片或内容,通常结合左右滑动按钮和指示器(小圆点)增强交互性。以下是基于原生JavaScript的实现方法。 HTML结构 构建轮播图的H…

js实现验证码

js实现验证码

使用Canvas生成图形验证码 在HTML中创建一个Canvas元素用于绘制验证码。通过JavaScript随机生成数字或字母组合,并添加干扰线、噪点等干扰元素增强安全性。 <canvas i…

js实现验证

js实现验证

验证表单输入 使用JavaScript验证表单输入是常见的需求。可以通过监听表单提交事件,检查输入字段是否符合要求。 document.getElementById('myForm').addEv…

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClipb…

js实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在H…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm…