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>
相关推荐
徐小夕16 小时前
花了一天时间,开源了一套精美且支持复杂操作的表格编辑器tablejs
前端·算法·github
Mintopia16 小时前
Next.js 单元测试究竟该选 JTest 还是 Vitest?
前端·javascript·next.js
Alice-YUE16 小时前
【CSS学习笔记3】css特性
前端·css·笔记·html
bug_kada16 小时前
告别页面卡顿!用DocumentFragment打造高性能DOM操作
前端
遂心_16 小时前
深入浅出 querySelector:现代DOM选择器的终极指南
前端·javascript·react.js
遂心_16 小时前
DOM元素内容修改全攻略:从innerHTML到现代API的最佳实践
前端·javascript·react.js
溯水流光16 小时前
React 源码解析
前端
Aomnitrix16 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
光影少年16 小时前
Typescript工具类型
前端·typescript·掘金·金石计划
北风GI16 小时前
如何在 vue3+vite 中使用 Element-plus 实现 自定义主题 多主题切换
前端