一、类的声明
function Aniaml () {
this.name = 'name';
}
//ES6x中类的声明
class Animal2 {
constructor () {
this.name = name;
}
}
二、类的实例化
console.log(new Aniaml());
console.log(new Aniaml2());
三、继承的几种方式及优缺点
继承的本质就是原型链。
1. 借助构造函数实现继承
原理:将父级的构造函数的this指向子构造函数的实例上去,导致父级函数的所有属性在子类中也有一份。
function Parent1 () {
this.name = 'parent1';
}
Parent1.prototype.say = function () {
console.log("say hi");
}
function Child1 () {
//apply、call: 将Parent1 函数在Child1 函数中执行,同时将其this指向Child1 函数。
//即改变this的指向,同时将Parent1 执行时的属性挂载到Child1 的类的实例上。
Parent1.call(this);
this.type = 'child1';
}
console.log(Child1().say()); // 会报错,因为父级构造函数的say方法在原型上,而不是通过this添加的
缺点:父级构造函数的原型对象上的属性不能被子构造函数继承,只能继承构造函数的属性。
2. 借助原型链实现继承
function Parent2 () {
this.name = 'parent2';
this.play = [1,2,3];
}
function Child2 () {
this.type = 'child2';
}
Child2.prototype = new Parent2();
console.log(new Child2().__proto__ === Child2.prototype); // true
console.log(new Child2().__proto__ .name); // "parent2"
var s1 = new Child2();
var s2 = new Child2();
console.log(s1.play, s2.play); //结果都是 [1,2,3]
s1.play.push(4);
console.log(s1.play, s2.play); //结果都是 [1,2,3,4]
缺点:修改一个实例的属性值,其他实例也会同样修改。
原因:原型链中的原型对象是公用的。
3. 组合方式实现继承
function Parent3 () {
this.name = 'parent3';
this.play = [1,2,3];
}
function Child3 () {
Parent3.call(this);
this.type = 'child3';
}
Child2.prototype = new Parent3();
var s3 = new Child3();
var s4 = new Child3();
s3.play.push(4);
console.log(s3.play, s4.play); //这里结果是不一样的
缺点:父级构造函数执行了两次
4. 组合继承的优化一
function Parent4 () {
this.name = 'parent4';
this.play = [1,2,3];
}
function Child4 () {
Parent3.call(this);
this.type = 'child4';
}
Child4.prototype = Parent4.prototype;
var s5 = new Child4();
var s6 = new Child4();
console.log(s5 instanceof Child4, s5 instanceof Parent4); //true
console.log(s5.constructor); // Parent4
实例.constructor指向父级构造函数,而不是子构造函数。
缺点:不能区分实例是子构造函数直接实例化的还是父级构造函数直接实例化的。
5. 组合继承的优化二 ------ 终极优化版
function Parent5 () {
this.name = 'parent5';
this.play = [1,2,3];
}
function Child5 () {
Parent3.call(this);
this.type = 'child5';
}
Child5.prototype = Object.create(Parent5.prototype);
Child5.prototype.constructor = Child5;
var s7 = new Child5(s7 instanceof Child5, s7 instanceof Parent5); //true
console.log(s7.constructor); //Child5
Object.create()创建的对象,原型对象就是括号中的参数