当前位置:首页 > 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实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js实现全屏

js实现全屏

实现全屏的基本方法 使用JavaScript实现全屏功能主要依赖Element.requestFullscreen()方法。现代浏览器均支持此API,但不同浏览器可能需要添加前缀。 // 触发全屏…

js类实现

js类实现

使用类实现 JavaScript 功能 在 JavaScript 中,类(Class)是一种语法糖,基于原型继承机制。通过 class 关键字可以更直观地定义对象模板。 基本类定义 class…

js实现路由

js实现路由

js实现路由的方法 在JavaScript中实现路由功能可以通过多种方式完成,以下是几种常见的方法: 使用原生JavaScript实现路由 通过监听window.onhashchange事件来实现基…

js实现排序

js实现排序

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

js 实现全屏

js 实现全屏

使用 requestFullscreen 方法 通过调用元素的 requestFullscreen 方法可以实现全屏。该方法兼容现代浏览器,但不同浏览器可能需要前缀。 const element =…