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>
相关推荐
孤水寒月3 小时前
基于HTML的悬窗可拖动记事本
前端·css·html
祝余呀3 小时前
html初学者第一天
前端·html
脑袋大大的4 小时前
JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
开发语言·javascript·性能优化
速易达网络5 小时前
RuoYi、Vue CLI 和 uni-app 结合构建跨端全家桶方案
javascript·vue.js·低代码
耶啵奶膘5 小时前
uniapp+firstUI——上传视频组件fui-upload-video
前端·javascript·uni-app
JoJo_Way5 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
视频砖家6 小时前
移动端Html5播放器按钮变小的问题解决方法
前端·javascript·viewport功能
lyj1689976 小时前
vue-i18n+vscode+vue 多语言使用
前端·vue.js·vscode
小白变怪兽8 小时前
一、react18+项目初始化(vite)
前端·react.js
ai小鬼头8 小时前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github