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>
相关推荐
上单带刀不带妹2 分钟前
手写 Vue 中虚拟 DOM 到真实 DOM 的完整过程
开发语言·前端·javascript·vue.js·前端框架
前端风云志4 分钟前
typescript结构化类型应用两例
javascript
杨进军23 分钟前
React 创建根节点 createRoot
前端·react.js·前端框架
ModyQyW38 分钟前
用 AI 驱动 wot-design-uni 开发小程序
前端·uni-app
说码解字44 分钟前
Kotlin lazy 委托的底层实现原理
前端
gnip1 小时前
总结一期正则表达式
javascript·正则表达式
爱分享的程序员1 小时前
前端面试专栏-算法篇:18. 查找算法(二分查找、哈希查找)
前端·javascript·node.js
翻滚吧键盘1 小时前
vue 条件渲染(v-if v-else-if v-else v-show)
前端·javascript·vue.js
vim怎么退出1 小时前
万字长文带你了解微前端架构
前端·微服务·前端框架
你这个年龄怎么睡得着的1 小时前
为什么 JavaScript 中 'str' 不是对象,却能调用方法?
前端·javascript·面试