原型链继承
function Parent(name,age){
this.name=name;
this.age=age;
this.subjects=['英语','数学','语文']
}
Parent.prototype.getname=function(){
console.log(this.name);
}
function Child(){
}
Child.prototype=new Parent('张三',18);
let c1=new Child();
let c2=new Child();
console.log(c1.name); //张三
console.log(c2.name); //张三
// 修改c1.name
c1.name='李四';
console.log(c1.name); //李四
console.log(c2.name); //张三
c1.subjects.push('化学');
console.log(c1.subjects); //['英语', '数学', '语文', '化学']
console.log(c2.subjects); //['英语', '数学', '语文', '化学']
//以上可以看出,修改父亲的基本数据类型和引用数据类型时,情况不一样
构造函数
function Parent(name){
this.name=name;
this.speak=function(){
console.log('speak');
}
}
Parent.prototype.getname=function(){
console.log('getname');
}
Parent.prototype.age='19';
function Child(){
Parent.call(this,"张三");
this.sex='f'
}
let c1=new Child();
console.dir(c1);
可见,通过构造函数进行继承,原型链上的属性和方法没法继承
组合继承
function Parent(){
this.name='zyzy';
this.speak=function(){
console.log('speak');
}
}
Parent.prototype.getname=function(){
console.log('getname');
}
Parent.prototype.age='19';
function Child(){
Parent.call(this); //构造函数
this.sex='f'
}
Child.prototype=new Parent(); //原型链
let c1=new Child();
console.dir(c1);
原型式继承(对象继承)
寄生式组合继承
function Parent(){
this.name='zyzy';
this.speak=function(){
console.log('speak');
}
}
Parent.prototype.getname=function(){
console.log('getname');
}
Parent.prototype.age='19';
function Child(){
Parent.call(this);
this.sex='f'
}
function CreateObj(o){
function F(){};
F.prototype=o;
return new F();
}
function extend(child,parent){
child.prototype=Object.create(parent.prototype);
child.prototype.constructor=child;
}
Child.prototype=new Parent();
let c1=new Child();
console.dir(c1);
参考添加链接描述