继承方式
一、原型链式
1. 基本思想:利用原型链实现继承
2. 实现
<script>
Plane.prototype.fly = function() {
console.log('fly');
}
function Plane(name){
this.name = name||'普通飞机';
this.color = ['red','blue','black'];
this.blood = 100;
}
var oPlane1 = new Plane();
var oPlane2 = new Plane();//共有属性,私有属性
AttackPlane.prototype = new Plane();
function AttackPlane (name) {}
var attcakPlane1 = new AttackPlane();
var attcakPlane2 = new AttackPlane('攻击机');
</script>
3. 缺点:
1)引用值共享,改变一个,两个属性都变
2)不能传参
4.优点
1)可以继承原型链上的属性
2)构造器不会变
二、构造函数
1. 基本思想:通过使用call、apply方法可以在新创建的对象上执行构造函数
2. 实现
<script>
Plane.prototype.fly = function () {
console.log('fly');
}
function Plane(name) {
this.name = name || '普通飞机';
this.color = ['red', 'blue', 'black'];
this.blood = 100;
}
function AttackPlane(name) {
Plane.call(this, name)
}
var attcakPlane1 = new AttackPlane('');
var attcakPlane2 = new AttackPlane('攻击机');
</script>
3.缺点
1)原型链上的属性和方法不能继承
4.优点
1)可以传参
2)引用值不会共享
三、组合继承
1.基本思想:利用构造继承和原型链组合
2.具体实现
<script>
Plane.prototype.fly = function () {
console.log('fly');
}
function Plane(name) {
this.name = name || '普通飞机';
this.color = ['red', 'blue', 'black'];
this.blood = 100;
}
AttackPlane.prototype = new Plane();
function AttackPlane (name) {
Plane.call(this,name)
}
var attcakPlane1 = new AttackPlane('攻击机');
var attcakPlane2 = new AttackPlane('');
AttackPlane.prototype.constructor = AttackPlane;//必须加上
</script>
3.缺点
1)构造器会改变
2)会执行两变函数
4.优点
1)可以继承原型链上的属性和方法
2)可以传参
3)引用值不会共享
原型式继承
1.基本思想:采用原型式继承并不需要定义一个类,传入参数obj,生成一个继承obj对象的对象
2.具体实现
<script>
var person = {
name: 'kevin',
friends: ['daisy', 'kelly']
}
function createObj(obj) {
function F(){}
F.prototype = obj;
return new F();
}
var person1 = createObj(person);
var person2 = createObj(person);
</script>
3.缺点
1) 引用值共享
2) 构造器改变
3)不能传参
4.优点
1)直接通过对象生成一个继承该对象的对象
五、寄生式继承
1.基本思想:创建一个仅仅用于封装继承过程的函数,然后在内部以某种方式增强对象,最后返回对象
2.具体实现
//创建一个函数,函数通过
var temp = function(){};
temp.prototype = Plane.prototype; AttackPlane.prototype = new temp();
//对对象的更改
//最后return new Object
3.优点
1)引用值可以共享
六、寄生组合式继承
1.基本思想:结合寄生式继承和组合式继承
2.具体实现
<script>
Plane.prototype.fly = function () {
console.log('fly');
}
function Plane(name) {
this.name = name || '普通飞机';
this.color = ['red', 'blue', 'black'];
this.blood = 100;
}
var temp = function(){};
temp.prototype = Plane.prototype;
AttackPlane.prototype = new temp();
AttackPlane.prototype.dan = function(){
console.log('发射导弹');
}
AttackPlane.prototype.constructor = AttackPlane;
function AttackPlane (name) {
Plane.call(this,name)
}
var attackPlane1 = new AttackPlane('');
var attackPlane2 = new AttackPlane('攻击机');
</script>
3.优点
1)引用值不共享
2)可以继承原型链上属性