原型链继承:
-
一个类继承父级属性和方法
-
使用原型链继承,将子类的原型对象修改成父级的实例对象
fn.prototype = new Father();
实例:
//提供一个父构造函数
function People(name,age){
this.name = name;
this,age = age;
}
//提供一个子构造函数
function Teacher(jobTitle,pay){
this.jobTitle =jobTitle;
this.pay = pay;
}
//给原型添加方法的语句一定要放在原型替换Teacher.prototype = new People();之后
//继承了People,同时还传递了实参;
//设置子构造函数的原型对象为父构造函数的一个实例对象,在实例对象上面设置属性和方法
Teacher.prototype = new People("张三",40);
var a = new.Teacher("语文老师",5000);
console.log(a.name); //张三
console.log(a.age);//40
借用构造函数:
-
实现原理
-
在解决原型对象中包含的引用数据类型值所带了的问题过程中,开发人员使用一种叫
借用构造函数
的技术,实现原理是,在子类的构造函数中,通过call()和appley()的形式,调用父类构造函数;以实现继承;
格式:
//1.子构造函数 function Son(param1,param2){ Father.call(this,param1,param2); }
实例:
//1.父构造函数 function Father(uname,age){ //this 指向父构造函数的实例对象 this.uname = uname;; this.age = age; } //2.子构造函数 function Son(uname,age,score){ //this 指向子构造函数的实例对象 Father.call(this.uname,age); //这个时候this 指向的就是子构造函数中的实例对象; this.score = score; } // var son = new Son("张三",18); console.log(son)
组合构造函数:
组合继承综合了原型链继承和调用构造函数继承(构造函数继承)将两者的优点结合了起来,
基本的思路就是使用原型链继承原型上的属性和方法,而通过构造函数继承实例属性,这样既可以把方法定义在原型上以实现重用,又可以让每个实例都有自己的属性
实例:
//1.父构造函数 function Father(uname,age,emotion){ //this 指向父构造函数的实例对象 this.uname = uname;; this.age = age; this.emotion = ['喜', '怒', '哀', '乐']; } //将父类的方法定义在父类的原型构造函数上 Father.prototype.eat = function(){ console.log("程序员秃头记") } //2.子构造函数 function Son(uname,age,score){ //this 指向子构造函数的实例对象 Father.call(this.uname,age); //这个时候this 指向的就是子构造函数中的实例对象; this.score = score; } //将子类的原型对象指向 父类的实例对象 Father.prototype = new Son() //son的原型对象已经需改成了Father的实例对象,但是Father的实力对象没有constructor属性; Father.prototype.constructor = Father //结果为false;应该为true;所以要修改Fatehr的constructor的属性 //修改 Father的constructor属性 Father.prototype.constructor = Fater; var t1 = new Son("张一闪",18,2000); console.log(t1)//输出结果为 (张一闪 18 )是父构造函数的实例对象 (2000)是子构造函数的实例对象; t1.eat();可以继承 父类原型对象上的方法。 t.emotion.push("愁")//添加到t.emotion最后; console.log(t.emotion);//输出结果为 ['喜', '怒', '哀', '乐' ,'愁']; var t2 = new Son("周老师",35,7000); console.log(t2.emotion); //解决了 原型链继承中 对复杂数据类型修改出现误差的情况
-