类与实例
类的声明
/*普通声明 */
var Animal = function () {
this.name = 'Animal';
};
/* es6中class的声明*/
class Animal2 {
constructor () {
this.name = 'Animal2';
}
}
生成实例
new Animal()
new Animal2()
//如果括号内没有参数,可以省略括号
类与继承、如何实现继承、继承的几种方式
1、利用构造函数实现继承
// 借助构造函数实现继承
function Parent1 () {
this.name = 'parent1';
}
function Child1 () {
Parent1.call(this); // call 和 apply 改变函数上下文 将this指向父类Parent1
this.type = 'child1';
}
console.log(new Child1);
打印结果如图
可以看出,Child1继承了Parent1的name,但是无法继承父类Parent1的方法
2、利用原型链实现继承
// 借助原型链实现继承
function Parent2 () {
this.name = 'parent2';
this.play = [1, 2, 3];
}
function Child2 () {
this.type = 'child2';
}
Child2.prototype = new Parent2(); //将Child2的prototype属性赋值为父类
console.log(new Child2().name); //打印结果为Parent2
缺点:利用这种继承方式的对象,生成的实例,共用了同一个__proto__属性,下面用代码展示
function Parent2 () {
this.name = 'parent2';
this.play = [1, 2, 3];
}
function Child2 () {
this.type = 'child2';
}
Child2.prototype = new Parent2(); //将Child2的prototype属性赋值为父类
console.log(new Child2().name); //打印结果为Parent2
var s1 = new Child2();
var s2 = new Child2();
console.log(s1.play, s2.play); //打印结果为 1,2,3 1,2,3
s1.play.push(4); //往S1实例中的paly属性增加一个4,
console.log(s1.play, s2.play); //打印结果为 1,2,3,4 1,2,3,4
可以看出,当生成多个实例的时候,修改其中一个实例的属性,其他实例的属性也会发生改变
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);
缺点:Parent3 执行了2次,第一次是构造,第二次是实例化。
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();
console.log(s5, s6);
缺点:无法确定实例化的原型对象是Child4还是Child4的父类Parent4
可以使用s5 instanceof Child4, s5 instanceof Parent4 验证
5、组合方式优化2
function Parent5 () {
this.name = 'parent5';
this.play = [1, 2, 3];
}
function Child5 () {
Parent5.call(this);
this.type = 'child5';
}
Child5.prototype = Object.create(Parent5.prototype);
这个方法的关键利用了Object.create()方法建立了一个中间值,隔断子类和父类使用同一个__proto__
面试时前2个方法必须得掌握。