ES5中的继承实现

在ES5中,是没有extends可用的,想要继承,就要自己手动解决了。 在继承里面,要解决的问题,简单的来看就是,属性还有方法的继承。

1.属性的继承

可以使用 Parent.call(this, ...args) 来解决。

如果这里不使用 call,直接将Child的原型指向了Parent,这里会出现引用类型数据共享问题

js 复制代码
// 这里如果有引用类型对象,会造成数据共享的问题
Child.prototype = new Parent();

2.方法的继承

子类继承父类的方法,简单点就可以直接将子类的原型指向父类的原型。

js 复制代码
Child.prototype = Parent.prototype

但是这里还会存在一个问题,就是子类修改方法,会影响父类。所以,这里需要另外建造一个对象,从而不影响父类,也就是使用Object.create()

js 复制代码
Child.prototype = Object.create(Parent.prototype)

3.原型链完整

保证instanceof和constructor正确

  • instanceof 应该能正确判断继承关系(child instanceof Parent 应为 true)。
  • child.constructor 应指向 Child 而不是 Parent。
js 复制代码
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child; // 修复 constructor

4.方法重写

子类方法覆盖父类方法,同时还能调用父类方法

在子类的原型上重写方法,然后在内部使用call来调用父类的方法,并写出子类自己的逻辑

js 复制代码
Child.prototype.sayName = function() {
  Parent.prototype.sayName.call(this); // 调用父类方法
  console.log("Child's sayName");
};

5.静态方法继承

js 复制代码
静态属性&方法
Parent.type = '0'
Parent.staticMethod = function(){}

例如这种该如何继承

在ES6上有Object.setPrototypeOf(Child, Parent)

在ES5上可以直接手动赋值

js 复制代码
for (var key in Parent) {
  if (Parent.hasOwnProperty(key)) {
    Child[key] = Parent[key];
  }
}

以上面5点来进行总结,ES5中的继承可以写成如下的形式

js 复制代码
function Parent(name) {
  this.name = name;
}

Parent.prototype.sayName = function() {
  console.log(this.name);
};

function Child(name, age) {
  Parent.call(this, name); // (1) 属性继承
  this.age = age;
}

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child; // (3) 修复 constructor

// (5) 静态方法继承(可选)
for (var key in Parent) {
  if (Parent.hasOwnProperty(key)) {
    Child[key] = Parent[key];
  }
}
相关推荐
Java展博11 小时前
[前端够用就好] 跨域报错时,浏览器到底在拦谁
前端·状态模式
用户1129361121911 小时前
npm 都提示成功了,node_modules 为什么还占着 370M?
linux·前端·后端
掘金安东尼12 小时前
Agent Harness 也有 benchmark:评分榜与评测工作台现状
前端·agent
digger_41912 小时前
从零理解 Electron:主进程、渲染进程、preload 与 IPC 实战
前端·electron
去伪存真13 小时前
别让你的 RAG 平台“花五份钱、答一份结巴的题”:幂等性架构的自我修养
前端·agent
snow@li14 小时前
前端:导入EXCEL并解析文件内容,demo
前端·javascript·vue.js
补码缩写15 小时前
压缩PNG不损失透明:只量化RGB、alpha原样留的减色流程
前端
TDengine (老段)15 小时前
TDengine IDMP 知识库与知识图谱
大数据·前端·物联网·知识图谱·时序数据库·tdengine·涛思数据
goehou16 小时前
PNG 转 WebP 不一定变小,我量了三类图
前端·性能优化·webp·sharp
夕水17 小时前
一个小小的颜色选择器,差点让我开发出一个组件库来
前端·javascript·typescript