继承:就是让一个对象可以具有另一个对象的特征
一个对象访问到另一个对象的属性
访问一个对象的属性或方法时,先在当前对象上找,找不到,就去这个对象的原型(对象)上找,找到了就能访问。
原型继承
将父类的对象赋值给子类的原型
function Person(){
this.eat = "能吃";
this.pao = "能跑";
}
var person= new Person();//实例化人类,得到人类对象
function Man(){
this.liqi = "特别大";
this.sport = "比较擅长"
}
Man.prototype = person;//将男人类的原型对象赋值为人类对象
function Woman(){
this.gao = "不高";
}
Woman.prototype = person;//将女人类的原型赋值为人类对象
var xiaomei = new Woman();
console.log(xiaomei.eat);//访问女人对象的eat属性 能吃
var ahao = new Man();//访问男人对象的eat属性 能吃
console.log(ahao.eat);
上下文调用函数
把父类构造函数体借用过来使用
上下文调用模式:
call
apply
bind
共同点就是能改变this的指向
call怎么改变?
可以调用函数,顺便将里面的this改成目标参数
function Animal(){
this.eat = "能吃";
this.pao = "能跑";
}
Animal.prototype.dong = function(){
console.log("能动");
}
function Cat(){
Animal.call(this); //这里的this指的是new Cat 的对象c
//将Animal中的this改成了c
//将Animal进行调用 执行这里的代码 this.eat ====> d.eat
//this.pao ===> c.pao
this.name = "猫";
}
var c = new Cat();
console.log(c);
//上下问调用的缺点:不能继承父类原型上的方法,
//所以在借用函数继承的基础上再进行原型的方式继承
组合继承
解决上下文调用模式的缺点
组合继承:使用上下文调用模式+原型来继承
function Animal(){
this.eat = "能吃";
this.pao = "能跑";
}
Animal.prototype.dong = function(){
console.log("能动");
}
function Cat(){
// 使用上下文调用,模式来继承
Animal.apply(this);
this.name = "猫";
}
//使用原型来继承
Cat.prototype = new Animal();
// 其实就没有必要让new Animal作为原型了,因为咱们只需要Animal的方法,
//这个方法不在Animal上,在原型上,
//所以可以将Animal的原型作为自己的原型(前提:就是Animal没什么用了)
Cat.prototype.constructor = Cat;
var c = new Cat();
console.log(c);
c.dong();
var a = new Animal();
console.log(a);
es6中的继承
class Animal{ // 父类
constructor(name){
this.eat = "能吃";
this.pro = "能跑"
this.name = name;
}
dong(){
console.log("能动");
}
}
class Rubbit extends Animal{ //子类-extends关键字并不能执行父类的constructor
constructor(name){
// 如果父类有constructor,子类这里(constructor里面)必须调用一个叫做super的方法
super(name); // 这是在执行父类的constructor
this.leg = "4条";
}
sport(){
console.log("跑的特别快");
}
}
var r = new Rubbit("兔子");
console.log(r);
//exteds 是es6提供的用来继承的语法
//function Person(name){
//this.name = name;
//this.eat = "能吃"
//}
//class Man extends Person{
// constructor(name){
// super(name);
// }
//}
//var m = new Man("豚豚");
//console.log(m);
语法:
class Animal{
//如果在实例化需要传递参数的话,就在这个类中,写一个函数,
//名字必须是constructor
}
var animal = new Animal();
console.log(animal); // Animal {}
class 子类 extends 父类{
constructor(){
super();
}
}
例:
class Animal{
constructor(name){
this.name = name;
}
dong(){
console.log("能动");
}
}
class Dog extends Animal{
constructor(name){
super(name);
this.jiao = "汪汪";
}
}
var ergou = new Dog("狗");
console.log(ergou); // Dog {name: "狗", jiao: "汪汪"}
ergou.dong(); // 能动
总结:
继承就是让一个类拥有另一个类的属性和方法。