转自https://blog.csdn.net/qq_17335153/article/details/52594134
ES6中已经封装实现了其他OO语言中的继承形式,Class Extends,这里主要记录js的原型继承和借用构造函数继承
一、原型链继承
function Super(){
this.name="小明";
}
Super.prototype.sayName = function(){
alert(this.name)
};
function Sub(){}
Sub.prototype = new Super();
var instance = new Sub();
instance.sayName();//小明
原型链继承的问题
//当超类中包含引用类型属性值时,其中一个子类的多个实例中,只要其中一个实例引用属性只发生修改一个修改,其他实例的引用类型属性值也会立即发生改变
//原因是超类的属性变成子类的原型属性
function Super(){
this.name="小明";
this.friends = ['小红','小强'];
}
Super.prototype.sayName = function(){
alert(this.name)
};
function Sub(){}
Sub.prototype = new Super();
var instance1 = new Sub();
var instance2 = new Sub();
instance1.friends.push('张三');
console.log(instance1.friends);//["小红", "小强", "张三"]
console.log(instance2.friends);//["小红", "小强", "张三"]
二、借用构造函数继承
function Super(){
this.name="小明";
this.friends = ['小红','小强'];
}
Super.prototype.sayName = function(){
alert(this.name)
};
function Sub(){
Super.call(this);
}
var instance1 = new Sub();
var instance2 = new Sub();
instance1.friends.push('张三');
console.log(instance1.friends);//["小红", "小强", "张三"]
console.log(instance2.friends);//["小红", "小强"]