关于JS继承我这边总结出来三种最常用,并且几乎无瑕疵的继承方法,分别是(构造函数+call)也称原型链继承,寄生式继承,ES6类继承
在说继承之前我们得先了解关于实例属性,静态属性,私有属性的内容,还有call,apply等方法的使用,关于这些,请慢慢挨着一一看之前的博客
1.构造函数加+call的方法,原型链继承
原理很简单,你要想继承父类构造函数和原型对象的方法很简单,父类构造函数实例就拥有了构造函数的方法,也可以访问原型对象的方法,那么我们来实现一下,请看代码
<script>
function Person(name,age,arr){
this.name=name;
this.age=age;
this.arr=arr
this.run=function(){
console.log("借调run方法成功")
}
this.eat=function(name,age){
console.log(name+age);
}
}
Person.prototype.k=function(){
console.log("我是原型对象");
}
function Student(name,age){
}
var p1=new Person("张三",20,[12,45,78,89,56,14]);
Student.prototype=p1;
//将原型对象指向的构造函数改变为Student
Student.prototype.constructor=Student;
//继承完成实例化
var stu1=new Student();
console.log(stu1.name);
console.log(stu1.age);
console.log(stu1.arr);
stu1.arr.push("zhuyu");
console.log(stu1.arr);
var stu2=new Student();
console.log(stu2.arr);
</script>
可以看出什么内容都继承下来了,但是有个纰漏是什么呢,你继承是父类的对象,那么会造成什么呢,父类有一个属性时数组这种引用类型,值时地址时,问题就来了。子类实例化多个对象使用的数组是一个,这不就GG了吗,想啊想,想啊想,前两篇博客不是说使用call是直接copy父类构造函数的内容么,没有引用类型共同操纵的问题,缺点就是继承不了原型对象的内容,那么来了综合一下,不就OK了吗。原理是子类构造函数有内容,就不会去原型中找,So,两个综合使用效果优越。看代码
function Person(name,age,arr){
this.name=name;
this.age=age;
this.arr=arr
this.run=function(){
console.log("借调run方法成功")
}
this.eat=function(name,age){
console.log(name+age);
}
}
Person.prototype.k=function(){
console.log("我是原型对象");
}
function Student(name,age,arr){
Person.call(this,name,age,arr)
}
var p1=new Person("张三",20,[12,45,78,89,56,14]);
Student.prototype=p1;
//将原型对象指向的构造函数改变为Student
Student.prototype.constructor=Student;
//继承完成实例化
var stu1=new Student("张三",20,[12,45,78,89,56,14]);
console.log(stu1.name);
console.log(stu1.age);
console.log(stu1.arr);
stu1.arr.push("zhuyu");
console.log(stu1.arr);
var stu2=new Student();
console.log(stu2.arr);
是不是子类创建的第二个数组就没有关联值了啊,到目前为止,第一种终于讲解完成,除了有赘余,使用还是完全没有问题的。
2.ES6中class继承
class Person {
constructor(options) {
this.color = options.color;
}
drive() {
return "失败";
}
}
var p = new Person({
name: "haha",
color: "red"
})
console.log(p.color);
console.log(p.drive());
class Student extends Person {
constructor(options) {
super(options);
this.title = options.title;
}
}
var stu = new Student({
title: "hihi",
color: "blue"
})
console.log(stu.title);
console.log(stu.color);