在ES6之前,JavaScript中的继承是通过原型链来实现的;下面对此进行分析:
一、原型链
function SuperType() {
this.property = true;
}
SuperType.prototype.getSuperValue = function () {
return this.property;
};
function SubType() {
this.subproperty = false;
}
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function () {
return this.subproperty;
};
var instance = new SubType();
console.log(instance.getSuperValue());//true
2、创建子类型的实例时,没有办法在不影响所有实例的情况下向超类型的构造函数传递参数;
基于以上缺点,实际应用中很少单独使用原型链,为解决这一问题,开发人员又提出一种借用构造函数的技术
二、借用构造函数
function SuperType(name) {
this.name = name;
this.friends = ['Alice'];
}
function SubType() {
SuperType.call(this, 'Jack');
this.age = 29;
}
var instance1 = new SubType();
var instance2 = new SubType();
instance1.friends.push('Bob');
console.log(instance1.name + ' ' + instance1.age);//Jack 29
console.log(instance2.name + ' ' + instance2.age);//Jack 29
console.log(instance1.friends);//["Alice", "Bob"]
console.log(instance2.friends);//["Alice"]
2、和原型链方式相比,借用构造函数的最大的优势是可以向父类传递参数(代码中的name参数);