当前位置: 首页 > article >正文

ES6 Class 转 ES5 实现

ES6 示例代码

class Animal {
  constructor(name) {
    this.name = name;
  }

  eat() {
    console.log(`${this.name} is eating`);
  }

  static sleep() {
    console.log("Sleeping");
  }
}

class Dog extends Animal { // 原型链继承 + 静态方法继承
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }

  bark() {
    super.eat(); // 调用父类构造函数
    console.log("Woof!");
  }
}

 

ES5 代码实现

// 父类Animal
function Animal(name) {
  this.name = name;
}

// 实例方法
Animal.prototype.eat = function() {
  console.log(this.name + " is eating");
};

// 静态方法
Animal.sleep = function() {
  console.log("Sleeping");
};

// 子类Dog
function Dog(name, breed) {
  Animal.call(this, name);
  this.breed = breed;
}

// 继承原型链
Object.setPrototypeOf(Dog, Animal); // 静态方法继承
Dog.prototype = Object.create(Animal.prototype, {
  constructor: { 
    value: Dog, 
    enumerable: false, // 方法自动绑定
  }
});

// 子类方法
Dog.prototype.bark = function() {
  Animal.prototype.eat.call(this);
  console.log("Woof!");
};

转换点

ES6ES5
class构造函数 + 原型方法
extendsObject.create() + Parent.call()
superParent.call(this, args)
super.method()Parent.prototype.method.call(this)
静态方法直接挂载到构造函数上
原型方法默认是不可枚举的‌enumerable: false

 

附加点:

虽然class的原型方法默认不可枚举,但可以通过Object.defineProperty()方法将enumerable属性设置为true,这样就可以遍历到这些方法了:

Object.defineProperty(obj, 'testMethod', {enumerable: true});
console.log(Object.keys(obj)); // ['testMethod']

 

 


http://www.kler.cn/a/584739.html

相关文章:

  • 基于JSP和SQL的CD销售管理系统(源码+lw+部署文档+讲解),源码可白嫖!
  • 基于深度学习的多模态人脸情绪识别研究与实现(视频+图像+语音)
  • PyTorch深度学习框架60天进阶学习计划 - 第18天:模型压缩技术
  • Jenkins实现自动化构建与部署:上手攻略
  • 【SpringBoot】深入剖析 Spring Boot 启动过程(附源码与实战)
  • 【Leetcode 每日一题】3306. 元音辅音字符串计数 II
  • 【每日学点HarmonyOS Next知识】防截屏、加载不同View、函数传参、加载中效果、沉浸式底部状态栏
  • Unity中WolrdSpace下的UI展示在上层
  • 【redis】lua脚本
  • C#中继承的核心定义‌
  • SQL语言的系统运维
  • springboot436-基于SpringBoot的汽车票网上预订系统(源码+数据库+纯前后端分离+部署讲解等)
  • 缓存及其问题解决
  • centos没有ll
  • sql-labs less-1-5wp
  • Flutter 从入门到进阶:构建跨平台应用的最佳实践
  • git使用命令总结
  • 【Linux】在VMWare中安装Ubuntu操作系统(2025最新_Ubuntu 24.04.2)#VMware安装Ubuntu实战分享#
  • 学习路之TP6 --重写vendor目录下的文件(新建命令)
  • DeepSeek结合Mermaid绘图(流程图、时序图、类图、状态图、甘特图、饼图)转载