一、用构造函数继承父类型属性
可以通过构造函数+原型对象
实现继承,称为组合继承
核心原理:通过call()把父类的this指向子类的this,这样就可以实现子类型继承父类型的属性
1、父构造函数
function Father(uname,age){
//this指向父构造函数的对象实例
this.uname=uname;
this.age=age;
}
2、子构造函数
function Son(uname,age){
//this指向子构造函数的对象实例
Father.call(this,uname,age);//把父的this改成了子的this
this.sex=sex;
}
var son=new Son("小李",18,男};//既继承了父类的属性又可以添加自身属性
console.log(son);
二、利用原型对象继承父类型方法
共有的属性写到构造函数里
共有的方法写到原型对象上
function Father(uname,age){
//this指向父构造函数的对象实例
this.uname=uname;
this.age=age;
}
Father.prototype.money=function(){
console.log("一百元");
}
function Son(uname,age){
Father.call(this,uname,age);
this.sex=sex;
}
//son.prototype=father.prototype;这样修改会有问题 如果修改了子原型对象 父原型对象也会一起变化
Son.prototype=new Father();
//如果利用对象的形式修改了原型对象,要利用constructor指回原来的构造函数
Son.prototype.constructor=Son;
//给子构造函数添加专门的方法
Son.prototype.exam=function(){
console.log("要考试");
}
var son=new Son("小李","18","男"};
console.log(son);
console.log(Father.prototype);//父构造函数里也会有exam方法??
console.log(Son.prototype.constructor);//Father