类的声明
/**
*es5
*/
var Animal = function () {
this.name = 'Animal';
};
/**
* es6中class的声明
*/
class Animal2 {
constructor () {
this.name = 'Animal2';
}
}
/**
* 实例化
*/
console.log(new Animal(), new Animal2());
1. 借助构造函数实现继承
原理:在子类里面执行父级的构造函数,将父级的构造函数的this指向子类构造函数的实例中去。
由于构造函数有自己的原型链,这种继承方式的缺点是父级的原型链上的属性并没有被子类所继承
function Parent1 () {
this.name = 'parent1';
}
Parent1.prototype.say = function () {
console.log("say hi")
};
function Child1 () {
//在子类里面执行父级的构造函数,将父级的构造函数的this指向子类构造函数的实例中去
Parent1.call(this);//apply
this.type = 'child1';
}
console.log(new Child1());
console.log(new Child1().say());
看打印结果Child1并没有say()这个方法
2. 借助原型链实现继承
将父级的构造函数赋给子类构造函数的原型对象
function Parent2 () {
this.name = 'parent2';
this.play = [1, 2, 3];
}
function Child2 () {
this.type = 'child2';
}
Child2.prototype = new Parent2();
console.log(new Child2());
new Child2().__proto__===Child2.prototype
// true
new Child2().__proto__.name
// "parent2"
实例化出的子类的_proto_会等于子类构造函数的原型对象,即父类的实例对象:new Parent2()
接下来看:
var s1 = new Child2();
var s2 = new Child2();
//改变s1的属性
s1.play.push(4);
console.log(s1.play, s2.play);
s1.proto===s2.proto
// true
缺点是:改一个实例对象的属性另一个也会跟着变,因为在原型链中两个子实例化对象的原型对象是共用的
3.组合方式:构造函数+原型链
在子类构造函数中执行父级构造函数,再将父级实例化对象赋给子类构造函数的原型对象
function Parent3 () {
this.name = 'parent3';
this.play = [1, 2, 3];
}
function Child3 () {
Parent3.call(this);
this.type = 'child3';
}
Child3.prototype = new Parent3();
var s3 = new Child3();
var s4 = new Child3();
s3.play.push(4);
console.log(s3.play, s4.play);
console.log(s3.constructor);
//function Parent3() {
this.name = 'parent3';
this.play = [1, 2, 3];
}
组合方式: 缺点是实例化子类的时候,父级的构造函数执行了两次,new Child3()的时候执行了一次,在原型链上new Parent3()又执行了一次。没有必要
4.组合继承的优化1
直接把父类的原型对象直接赋给子类的原型对象,这样就实现了继承
原型对象在这里只是引用不会执行,只是在子类实例化时才执行
function Parent4 () {
this.name = 'parent4';
this.play = [1, 2, 3];
}
function Child4 () {
Parent4.call(this);
this.type = 'child4';
}
//原型对象在这里只是引用不会执行
Child4.prototype = Parent4.prototype;
var s5 = new Child4();
var s6 = new Child4();
s5.play.push(4);
console.log(s5, s6);
console.log(s5 instanceof Child4, s5 instanceof Parent4);
// true true
console.log(s5.constructor);
//function Parent4() {
this.name = 'parent4';
this.play = [1, 2, 3];
}
因为原型对象公共了,所以无法区分子类的实例化对象到底是谁的直接实例化对象
因为s5.constractor=Child4 而Child4=Child4.prototype.constractor
因为Child4.prototype = Parent4.prototype, 所以Child4 = Parent4.prototype.constractor;继而s5.constractor=Parent4.prototype.constractor
子类的实例化对象的constractor指向了父类的constractor
4.组合继承的优化2
Object.create()通过创建中间对象作为桥梁,将父类和子类的隔离,再重新定义子类构造函数的原型对象的constractor
特点:原型对象作为参数
function Parent5 () {
this.name = 'parent5';
this.play = [1, 2, 3];
}
function Child5 () {
Parent5.call(this);
this.type = 'child5';
}
Child5.prototype = Object.create(Parent5.prototype);
Child5.prototype.constructor=Child5;
var s7 = new Child5();
console.log(s7 instanceof Child5,s7 instanceof Parent5);
console.log(s7.constructor);
实例化继承关系还在,从哪里直接实例化来的已经找到