JS面试题5——JS继承有哪些方式

  1. ES6
javascript 复制代码
/* 此时的Child上只有name属性,没有age属性 */
<script>
// 父
class Parent{
  constructor(){
    this.age = 18;
  }
}
// 子
class Child{
  constructor(){
    this.name = '张三';
  }
}
let o1 = new Child();
console.log(o1, o1.name, o1.age); // 打印出:Child {name: '张三'} '张三' undefined
</script>
/* 此时的Child上既有name属性,又有age属性 */
<script>
// 父
class Parent{
  constructor(){
    this.age = 18;
  }
}
// 子
class Child extends Parent{
  constructor(){
    super();
    this.name = '张三';
  }
}
let o1 = new Child();
console.log(o1, o1.name, o1.age); // 打印出:Child {age: 18, name: '张三'} '张三' 18
</script>
  1. 原型链继承
javascript 复制代码
<script>
// 父
function Parent() {
  this.age = 20;
}
// 子
function Child() {
  this.name = '李四';
}
Child.prototype = new Parent()
let o1 = new Child();
console.log(o1, o1.name, o1.age); // 打印出:Child {name: '李四'} '李四' 20
</script>
  1. 借用构造函数继承
javascript 复制代码
<script>
// 父
function Parent(){
  this.age = 22;
}
// 子
function Child(){
  this.name = 'xiongxinyu';
  Parent.call(this); // 改变this指向
}
let o3 = new Child();
console.log(o3,o3.name,o3.age); // 打印出:Child {name: 'xiongxinyu', age: 22} 'xiongxinyu' 22
</script>
  1. 组合式继承
javascript 复制代码
<script>
// 父
function Parent(){
  this.age = '24'
}
// 子
function Child(){
  Parent.call(this)
  this.name = 'y'
}
Child.prototype = new Parent();
var o4 = new Child();
console.log(o4,o4.name,o4.age); // 打印出:Child {age: '24', name: 'y'} 'y' '24'
</script>
相关推荐
java1234_小锋9 分钟前
【技术专题】CSS3 网页技术 - CSS3 布局进阶
前端·css·css3
zhippt_101431 分钟前
只剩截图没有源文件?图转PPT把图片还原成可编辑幻灯片
前端·人工智能·powerpoint
shmily麻瓜小菜鸡1 小时前
TypeScript 知识点补充(第三部分:工程化与高级类型)
前端·javascript·typescript
10岁的博客1 小时前
Chrome 扩展安全攻防实录:从权限模型到真实漏洞复盘
前端·chrome·安全
QianhangQianping2 小时前
WebSocket实时推送+ HTTP 定时轮询:一块大屏两套取数怎么不打架
前端·websocket·网络协议·http·低代码·架构·数据可视化
Frag0ut2 小时前
Notepad++ 零基础入门:从记事本到代码编辑器的平滑过渡(2026最新版)
python·编辑器·html·json·notepad++·markdown·记事本
滼2 小时前
AI 数据安全面试应答框架:从大框架到小点
大数据·人工智能·安全·面试·安全架构
Eider19982 小时前
Python基础知识之并发相关-2
开发语言·前端·python
用户69371750013842 小时前
AI 能写代码,但工程架构还是应该由人来定
前端·后端
Hilaku2 小时前
前端的技术判断力是怎么练出来的?
前端·javascript·程序员