当前位置:首页 > JavaScript

js 实现封装 多态

2026-03-15 21:19:39JavaScript

封装与多态在 JavaScript 中的实现

封装

封装是面向对象编程的核心概念之一,通过隐藏对象的内部细节并暴露可控的接口来实现。JavaScript 可以通过闭包、构造函数、类(ES6)等方式实现封装。

闭包实现封装

js 实现封装 多态

function createCounter() {
  let count = 0; // 私有变量

  return {
    increment: function() {
      count++;
    },
    getCount: function() {
      return count;
    }
  };
}

const counter = createCounter();
counter.increment();
console.log(counter.getCount()); // 1
console.log(counter.count); // undefined(无法直接访问私有变量)

ES6 类实现封装

class Counter {
  #count = 0; // 私有字段(ES2022)

  increment() {
    this.#count++;
  }

  getCount() {
    return this.#count;
  }
}

const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 1
console.log(counter.#count); // 报错(私有字段不可外部访问)

多态

多态允许不同对象对同一方法调用做出不同响应。JavaScript 通过原型链和动态类型天然支持多态。

js 实现封装 多态

基于原型链的多态

class Animal {
  makeSound() {
    console.log("Some generic sound");
  }
}

class Dog extends Animal {
  makeSound() {
    console.log("Bark");
  }
}

class Cat extends Animal {
  makeSound() {
    console.log("Meow");
  }
}

const animals = [new Animal(), new Dog(), new Cat()];
animals.forEach(animal => animal.makeSound());
// 输出:
// Some generic sound
// Bark
// Meow

接口式多态(鸭子类型) JavaScript 不检查类型而是检查行为,只要对象具有所需方法即可:

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

const dog = { makeSound: () => console.log("Woof") };
const robot = { beep: () => console.log("Beep") };

playSound(dog); // Woof
playSound(robot); // 无输出(缺少makeSound方法)

结合封装与多态的完整示例

class Shape {
  #color; // 私有字段

  constructor(color) {
    this.#color = color;
  }

  getColor() {
    return this.#color;
  }

  area() {
    throw new Error("Abstract method must be implemented");
  }
}

class Circle extends Shape {
  #radius;

  constructor(color, radius) {
    super(color);
    this.#radius = radius;
  }

  area() {
    return Math.PI * this.#radius  2;
  }
}

class Square extends Shape {
  #side;

  constructor(color, side) {
    super(color);
    this.#side = side;
  }

  area() {
    return this.#side  2;
  }
}

const shapes = [
  new Circle("red", 5),
  new Square("blue", 4)
];

shapes.forEach(shape => {
  console.log(`Color: ${shape.getColor()}, Area: ${shape.area()}`);
});
// 输出:
// Color: red, Area: 78.53981633974483
// Color: blue, Area: 16

JavaScript 的动态特性使得多态不需要显式接口定义,只需对象实现相应方法即可。封装则通过闭包或现代语法(如私有字段)来实现数据保护。

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

相关文章

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

js实现预览

js实现预览

文件上传预览实现 使用JavaScript实现文件上传预览功能,可以通过FileReader对象读取文件内容并显示预览。以下代码支持图片、文本和PDF文件的预览: // HTML部分需要包含…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

vue实现js休眠

vue实现js休眠

实现 JavaScript 休眠的方法 在 Vue 中实现 JavaScript 休眠(延迟执行)可以通过以下方式实现。由于 JavaScript 本身没有内置的 sleep 函数,通常使用 Prom…

js实现排序

js实现排序

数组排序方法 JavaScript提供了内置的sort()方法用于数组排序。默认情况下,sort()将元素转换为字符串并按照Unicode码点排序。对于数字排序,需传入比较函数。 const num…

js 实现图片轮播

js 实现图片轮播

基础实现方案 使用HTML、CSS和JavaScript创建一个简单的图片轮播。HTML部分定义轮播容器和图片,CSS负责样式布局,JavaScript处理轮播逻辑。 <div class="…