JS中的继承(上)

为什么要继承

因为一个类(构造函数)中可能存在大量公用的属性和方法,利用对象的继承可以简化代码。

案例

如下的案例如何实现继承呢?

// 父类公共的属性和方法
function Person(){
    this.name = 'why'
}

Person.prototype.eating = function(){
    console.log(this.name + 'eating~');    
}

// 子类:特有的属性和方法
function Student(){
   this.sno = 111 
}
Student.prototype.studying = function(){
    console.log(this.name + 'studying~');    
}
let stu = new Student()
console.log(stu.name);
stu.eating()

利用原型链,解决方案1

可以利用原型链,只需一行代码,大家画个内存图就很好理解了。

// 父类公共的属性和方法
function Person(){
    this.name = 'harry'
}

Person.prototype.eating = function(){
    console.log(this.name + 'eating~');    
}

// 子类:特有的属性和方法
function Student(){
   this.sno = 111 
}

//加载创建完子类之后
Student.prototype = new Person()  //***利用原型链
//或者这么写
// var p =  new Person()
// Student.prototype = p


Student.prototype.studying = function(){
    console.log(this.name + 'studying~');    
}
let stu = new Student()
console.log(stu.name);
stu.eating()
该方案的弊端
  1. 打印stu对象,继承属性看不到比如stu.name,因为原型上的属性是打印不了的。
  2. 如果创建出两个stu对象,两个对象会相互影响,看下面的代码
// 父类公共的属性和方法
function Person(){
    this.name = 'harry'
    this.friends = [] //对应的是一个数组
}

Person.prototype.eating = function(){
    console.log(this.name + 'eating~');    
}

// 子类:特有的属性和方法
function Student(){
   this.sno = 111 
}

Student.prototype = new Person()  //***利用原型链

Student.prototype.studying = function(){
    console.log(this.name + 'studying~');    
}
let stu1 = new Student()
let stu2 = new Student()

stu1.friends.push("lbj")

//直接修改对象上的属性,是给本对象添加了一个新属性
stu1.name = "lebro" //它会给自己添加name属性,不会改原型的属性
console.log(stu2.name); //这个不影响
//获取引用,修改引用的值,会相互影响
console.log(stu1.friends);
console.log(stu2.friends);  //两个对象
  1. 在实现类的过程中都没有传参数,因为无法传参(子类创建出的实例属性无法传到父类中)。

constructor stealing(借用构造函数),解决方案2(改进方案1)

这样子三个问题就都解决了

// 父类公共的属性和方法
function Person(name,age,friends){
    //this = stu 这里this就是stu1或者stu2了
    this.name = name
    this.age = age
    this.friends = friends
}

Person.prototype.eating = function(){
    console.log(this.name + 'eating~');    
}

// 子类:特有的属性和方法
function Student(name,age,friends,sno){
    //借用的调了一下Person这个构造函数
   Person.call(this,name,age,friends) //Student(stu1,stu2)的this
   this.sno = sno
}

Student.prototype = new Person()  //***利用原型链


//Student.prototype = Person.prototype
Student.prototype.studying = function(){
    console.log(this.name + 'studying~');    
}
let stu1 = new Student('harry',18,['kobe'],111)
let stu2 = new Student('harry',18,['kobe','looo'],112)

stu1.friends.push("lbj") 
console.log(stu1); //Person { name: 'harry', age: 18, friends: [ 'kobe', 'lbj' ], sno: 111 }
console.log(stu2); 

仍然存在的弊端:

  1. Person函数被调用了n次,n为创建子类的次数。
  2. stu原型对象上会多出一些属性,但是这些属性是没有存在的必要。

在我的下一篇文章中会介绍JS更为完善的继承方法。

来自本人掘金文章 https://juejin.cn/post/7111635920679338020/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值