JS中的继承,表示子类去继承父类的属性。
- 1、原型链继承:让Child去找Parent上的属性或方法,如果找到的是一个引用数据类型,实际上找到的是一个地址,子类对象通过这个地址修改了Parent上的数据,其它得到子类对象也受到影响。
2、构造函数继承(Call继承):将Parent上的属性和方法添加到Child身上。使用call来复制一遍Parent上的操作。
1、原型链继承
让子类的原型指向父类的对象:
Child.protorype = new Parent();
同时让子类的原型对象中的constructor有正确的指向:
Child.prototype.constructor = Child;
<script>
function Parent(){
this.name = "ParentName"
}
Parent.prototype.getName = function(){
console.log(this.name);
}
function Child(){}
//原型链继承
Child.prototype = new Parent();
Child.prototype.constructor = Child;
let c = new Child;
c.getName(); //可以访问
</script>
缺点:
- 1、如果父中的数据类型是引用数据类型,子对象修改了,其他子对象也会受影响(父中的数据如果时引用数据类型会被所有的子共享)
- 2、创建Child对象时不能传参
2、构造函数继承(call继承)
将Parent上的属性和方法添加到Child身上。使用call来复制一遍Parent上的操作。
<script>
function Parent(){
this.hobby = ["eat","run"];
this.name = "parentName";
}
function Child(){
//核心
Parent.call(this);
}
let c1 = new Child();
let c2 = new Child();
</script>
3、组合继承
将原型链继承和构造函数继承相结合
4、寄生组合继承
借助中间函数
function Temp(){ }
Temp.protorype = Parent.protorype;
Child.protorype = new Temp();
Child.protorype.constructor = Child;