1、继承的总结
1、原型继承:
function Super(name) {
this.name = name;
this.su = ['2', '4', '5'];
}
Super.prototype.sayName = function () {
};
function Sub() {
}
Sub.prototype = new Super();
var n = new Super('xiao');
var p = new Sub();
p.sayName();//继承了构造函数的属性和方法,和原型的方法
n.su.push(6);
n.su// '2', '4', '5',‘6’
p.su// '2', '4', '5',‘6’
缺点: 构造函数的引用类型都已经复用
2、构造函数的继承:
function Super() {
}
function Sub() {
Super.call(this, arguments);
}
var s = new Super();
var sub = new Sub();
解决的问题:为了解决引用的不用复用
缺点:不能继承原型的类型
3、组合继承
function Super(name) {
this.name = name;
this.su = ['2', '4', '5'];
}
Super.prototype.sayName = function () {
};
function Sub() {
Super.apply(this, arguments);
}
Sub.prototype = new Super();
Sub.prototype.constructor = Sub;
var n = new Super('xiao');
var p = new Sub();
p.sayName();//继承了构造函数的属性和方法,和原型的方法
n.su.push(6);
n.su// '2', '4', '5',‘6’
p.su// '2', '4', '5',‘6’
4、寄生式继承
function anotherCreat(obj) {
var clone = object(obj);
clone.say = function () {
alert('hi');
}
return clone;
}
var obj = {
name: 'a',
atrr: '3'
}
var a = anotherCreat(obj)
a.say()//
5、寄生组合继承
// 这个是终端的继承
function Super() {
}
Super.prototype.sayAge = function () {
};
function Sub() {
Super.call(this);
}
inherits();
function inherits(Sub, Super) {
prototype = object(Super.prototype)
prototype.constructor = Sub;
Sub.prototype = prototype;
}
var a = new Super();
var b = new Sub();
Sub.prototype.say = function () {
}
6、es6 的继承
class A{}
class B{}
class A extends B{
constructor(){
super();
}
}