知识点:
类与实例:
- 类的声明
- 生成实例
类与继承:
- 如何实现继承
- 继承的几种方式
1. 类与实例
// 类的声明
var Animal = function () {
this.name = 'Animal';
};
// ES6 中 class 的声明
class Animal2 {
constructor () {
this.name = 'Animal2';
}
};
// 实例化
console.log(new Animal(),new Animal2());
2. 类与继承
// 借助构造函数实现继承
function Parent1 () {
this.name = 'parent1';
}
Parent1.prototype.say = function () {
console.log('say');
};
function Child1 () {
Parent1.call(this);
this.type = 'child1';
}
console.log(new Child1(),new Child1.say()); // 这里不能继承原型对象中的 say 方法
// 借助原型链实现继承
function Parent2() {
this.name = 'Parent2';
this.play = [1, 2, 3, 4];
}
Parent2.prototype.say = function() {
console.log('say');
}
function Child2() {
this.type = 'child2';
}
Child2.prototype = new Parent2();
var s1 = new Child2;
var s2 = new Child2;
console.log(s1.play, s2.play);
s1.play.push(5);
console.log(s1.play, s2.play);
console.log(s1.say()); //say undefined
// 组合方式
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); //[1,2,3,4], [1,2,3]
// 组合继承的优化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);
console.log(s5 instanceof Child4 === s5 instanceof Parent4); // true
console.log(s5.constructor); // 指向实例对象 Parent4 而不是 Child4
// 组合继承的优化2
function Parent5 () {
this.name = 'parent4';
this.play = [1,2,3];
}
function Child5 () {
Parent5.call(this);
this.type = 'child5';
}
Child5.prototype = Object.creat(Parten5.prototype); //将 Parent5 的原型对象拷贝过来,解决了 constructor 不指向自己构造函数的问题