面向对象

继承的几种方法归整


原型继承:构造函数原型链继承
借调继承:借用构造函数调用冒充继承,借调实现的继承,不是真正的继承,只是借用构造函数中的属性或方法。
组合继承:组合 构造函数的借调继承和原型的继承优点;

原型继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

function Father(name,age){
this.name = name;
this.age = age;
}
Father.prototype.eat = function(){
console.log(this.name+'吃饭了')
}
let f1 = new Father('zhangxing',24);
function Son(){

}
Son.prototype = f1
let s1 = new Son();
s1.eat();


// ①:当 Son.prototype指向Father的时候,他就已经是父类型的Son了。

// ②:s1.eat();s1中没有此方法,该方法在父类型原型中,当s1访问时,现在s1中查找,若没有则向他指向的原型中去查找该方法,若还是没有,则继续往上面的原型中查找。这样就形成了一条原型链。

// ③:通过原型链实现了继承

借调继承 借用构造函数调用冒充继承,借调实现的继承,不是真正的继承,只是借用构造函数中的属性或方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Fn(name,age){
this.name = name;
this.age = 20;
}
function Son(name,age,sex){
Fn.call(this,name,age);
this.sex = sex;
}

let s1 = new Son('zhangxing',24,'nv');
console.log(s1)


// 注意:借调缺点:call是冒充继承,不是真正的继承,所以不能访问原构造函数的原型中的属性或方法。

组合继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function Fn(name,age){
this.name = name;
this.age = age;
if((typeof Fn.prototype.eat)!="function"){
Fn.prototype.eat = function(){
console.log(this.name+'吃饭了')
}
}
}

function Son(name,age,sex){
Fn.call(this,name,age)//借调 Fn的属性
this.sex = sex;
}

Son.prototype = new Fn();
var s1 = new Son('zhangxing',20,'nv');
s1.eat();