JavaScript继承的三种方 面试面向对象

面向对象

看这篇的同学,先要学会原型链,若还不会看我的上一篇文章原型链
https://blog.csdn.net/Gueyue/article/details/102545419

类的声明
// 类的声明
  function Animal(){
    this.name = name
  }

  // ES6类的声明
  class Animal2{
    constructor(){
      this.name = name
    }
  }

  //实例化
  console.log(new Animal('Animal'),new Animal2('Animal2'))
继承
借助原型链实现继承
  • 特点:
    • 子类的实例也是父类的实例
    • 可以方便的基础父类型的原型中的方法,但是属性的继承无意义
  • 缺点:
    • 只执行一次,无法给属性传值
    • 属性的继承无意义
function Person() {
    this.name = name
    this.age = age
}
Person.prototype.sayHi = function(){
    console.log('大家好,我是'+this.name)
}
function Student() {
  this.score = 100;
}
Student.prototype = new Person(); //改变prototype的指向
Student.prototype.constructor = Student;  //改变构造函数

var s1=new Student()
s1.syHi() //大家好,我是undefined
console.log(s1.age) //undefined
  
构造继承
  • 核心:

  • 在子类的内部调用父类,通过call改变父类中this的指向

  • 等于是复制父类的实例属性给子类

  • 特点:

  • 创建子类实例时,可以向父类传递参数

  • 可以实现多继承

  • 可以方便的继承父类型的属性,但是无法继承原型中的方法

  • 缺点:

    • 实例并不是父类的实例,只是子类的实例
    • 无法继承原型中的方法
    • 无法实现函数复用,每个子类都有父类实例函数的副本,影响性能
 function Person(name,age){
    this.name = name
    this.age = age
  }

  Person.prototype.sayHi = function(){
    console.log('大家好,我是'+this.name)
  }

  function Student(name,age,score){
    Person1.call(this,name,age)
    this.score = score
  }

  var s1 = new Student('zs',18,88)
  //s1.sayHi() //报错 not a function
  console.log(s1 instanceof Person) //false
  console.log(s1.name)  //zs
组合继承

特点:既是子类的实例,也是父类的实例

​ 可传参

​ 函数可复用

function Person(name,age){
    this.name = name
    this.age = age
  }

  Person.prototype.sayHi = function(){
    console.log('大家好,我是'+this.name)
  }

  function Student(name,age,score){
    Person1.call(this,name,age)
    this.score = score
  }
	Student.prototype = new Person()
	Student.prototype.constructor = Student
	var s1 = new Student('zs',18,88)
	
    var s1 = new Student('zs',18,88)
  	s1.sayHi() //大家好,我是zs
  	console.log(s1 instanceof Person) //true
  	console.log(s1.name)  //zs

上述构造函数执行了两次并没有必要

可以优化为

function Person(name,age){
    this.name = name
    this.age = age
  }

  Person.prototype.sayHi = function(){
    console.log('大家好,我是'+this.name)
  }

  function Student(name,age,score){
    Person1.call(this,name,age)
    this.score = score
  }
	Studnet.prototype = Object.create(Person.prototype)
	Student.prototype.constructor = Student
	var s1 = new Student('zs',18,88)
	
    var s1 = new Student('zs',18,88)
  	s1.sayHi() //大家好,我是zs
  	console.log(s1 instanceof Person) //true
  	console.log(s1.name)  //zs
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值