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>
相关推荐
毛骗导演5 分钟前
@tencent-weixin/openclaw-weixin 源码ContextToken 持久化改造:实现微信自定义消息发送能力
前端·架构
爱丽_5 分钟前
Pinia 状态管理:模块化、持久化与“权限联动”落地
java·前端·spring
进击的尘埃14 分钟前
从多仓到 Monorepo 的渐进式迁移:Git 历史保留、依赖收敛与缓存调优
javascript
SuperEugene33 分钟前
TypeScript+Vue 实战:告别 any 滥用,统一接口 / Props / 表单类型,实现类型安全|编码语法规范篇
开发语言·前端·javascript·vue.js·安全·typescript
我是永恒1 小时前
上架一个跨境工具导航网站
前端
电子羊1 小时前
Spec 编程工作流文档
前端
GISer_Jing1 小时前
从CLI到GUI桌面应用——前端工程化进阶之路
前端·人工智能·aigc·交互
还是大剑师兰特1 小时前
Vue3 报错:computed value is readonly 解决方案
前端·vue.js
leaves falling2 小时前
有效的字母异位词
java·服务器·前端
我真会写代码2 小时前
Spring面试高频题:从基础到源码,通俗拆解+避坑指南
java·spring·面试