前端面试--一篇搞懂 原型链构造函数实现的继承

实现继承,是为了代码的复用,在js中使用原型链实现继承
大概思路:
1.父类 Person
2.子类 Student
3.两者建立关系通过原型
4.当我们在 Student上边 找不到想要获取的属性的时候,可以通过原型 去父级类 Person上边找
问题:
1.直接使用
Student.prototype=Person
弊端:这样当我们 Student.prototype.func 添加方法的时候,添加到了 Person父级类上边,其他类继承时候也会继承不必要的属性
2.通过定义一个中间的类
var p=new Person()
Student.prototype=p
这样继承可以避免 1 的问题,但是,这样当new 的时候,p会产生多余开辟的对象,会产生Person里相同的属性,造成多余 的 属性
3.现在我们需要做的是 ,拿到一个指向 父类原型的 对象,但是又不能使用上边两种操作
我们可以使用 let obj=Object.create(o)

这样只继承了,添加到Person.prototype 上边的内容,实现 继承 Person函数体内的内容 ,我们要使用构造函数法,在子类里边调用父类函数。
function Student(){
Person.call(this)
}

具体实现代码:

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

Person.prototype.running=function(){
  console.log(this.name + '在跑步~~')
}
function Student(sno,name,age,friends){
    Person.call(this,name,age,friends)
    this.sno=sno
}



Student.prototype=Object.create(Person.prototype)
Object.defineProperty(Student.prototype,'constructor',{
  configurable:false,
  enumerable:false,
  value:Student,
  writable:false
})  //修改子类的构造函数名称

Student.prototype.eatting=function(){
  console.log(this.name + '在吃东西~~')
}

let stu1=new Student('123','aaa',12,['a','b'])
let stu2=new Student('23','bba',18,['b'])


stu1.eatting()
stu2.running()


stu1.friends.push("hhh")
console.log(stu1.friends)
console.log(stu2.friends)

console.log(stu1.constructor.name)

console.log(stu1,stu2)




以上分析了继承的两个关键点:
1.继承Person.prototype上边的属性
2.继承Person 函数体内 的属性
掌握这两个点,大概就能手写一个 使用原型链+构造函数实现的继承了.

个人学习散写,有问题评论区。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值