实现继承,是为了代码的复用,在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 函数体内 的属性
掌握这两个点,大概就能手写一个 使用原型链+构造函数实现的继承了.
个人学习散写,有问题评论区。