当前位置:首页 > JavaScript

js 实现封装 多态

2026-04-07 14:43:01JavaScript

封装与多态在 JavaScript 中的实现

封装

封装的核心是通过限制对对象内部状态的直接访问,仅暴露必要的接口。在 JavaScript 中可以通过闭包、模块模式或 ES6 的 class 语法实现。

闭包实现私有变量

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

  this.increment = function() {
    count++;
    console.log(count);
  };

  this.getCount = function() {
    return count;
  };
}

const counter = new Counter();
counter.increment(); // 输出 1
console.log(counter.count); // undefined

ES6 Class 实现

class Counter {
  #count = 0; // 私有字段(现代浏览器支持)

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

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

const counter = new Counter();
counter.increment(); // 输出 1
console.log(counter.#count); // 报错

多态

多态允许不同对象对同一方法调用做出不同响应。JavaScript 通过原型继承和接口实现(鸭子类型)支持多态。

原型继承实现

class Animal {
  speak() {
    throw new Error("必须实现 speak 方法");
  }
}

class Dog extends Animal {
  speak() {
    return "汪汪";
  }
}

class Cat extends Animal {
  speak() {
    return "喵喵";
  }
}

function makeSound(animal) {
  console.log(animal.speak());
}

makeSound(new Dog()); // 汪汪
makeSound(new Cat()); // 喵喵

鸭子类型实现

js 实现封装 多态

function makeSound(obj) {
  if (typeof obj.speak === 'function') {
    console.log(obj.speak());
  }
}

const dog = { speak: () => "汪汪" };
const cat = { speak: () => "喵喵" };

makeSound(dog); // 汪汪
makeSound(cat); // 喵喵

结合封装与多态

class Shape {
  #color;

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

  getColor() {
    return this.#color;
  }

  area() {
    throw new Error("必须实现 area 方法");
  }
}

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(`颜色: ${shape.getColor()}, 面积: ${shape.area()}`);
});

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

相关文章

js实现图片上传

js实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js实现论坛

js实现论坛

实现论坛的基本功能 使用JavaScript实现一个论坛需要结合前端和后端技术。前端可以使用React、Vue或Angular等框架,后端可以选择Node.js配合Express或Koa框架。数据库可…

js jquery

js jquery

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够…

js实现目录

js实现目录

实现目录的基本思路 在JavaScript中实现目录功能通常涉及以下几个核心步骤:解析文档中的标题元素(如h1-h6),动态生成目录结构,并添加交互逻辑(如点击跳转)。以下是具体实现方法: 解析标题…

js节流实现

js节流实现

节流的概念 节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于滚动事件、窗口调整等高频触发的场景。 基础实现方法 使用时间戳判断是否执行函数: fun…