继承前提---- 继承分为两种:类与类之间的继承,类创造实例对象
funtion parent(){
//私有属性
var name ;
//私有方法
var addName = function(){};
//公有属性
this.sex;
//公有方法
this.addSex = function(){};
}
parent.prototype = {
//共有属性(原型属性)
age: 11,
//共有方法
setAge: function(){}
}复制代码
1、类式继承:(类与类之间的继承)
function parent(){ this.name = [];
}
parent.prototype = {
age: 12
}
//声明子类
function child(){}
child.prototype = new parent();
//缺陷:
//1、父类的公共属性为引用类型时,子类生成的实例对象之间的属性会相互影响
let child_example1 = new child();
let child_example2 = new child();
console.log(child_example1.name);//[]
console.log(child_example2.name);//[]
child_example1.name.push(1);
console.log(child_example2.name);//[1]
//2、子类实例无法初始化父类原型中的属性和方法
复制代码
2、构造函数继承:(类与类之间的继承)
function parent(name){
this.name = name;
}
parent.prototype = {
sex: '男'
}
function child(){
parent.call(this,'ltp');
}
let child_example = new child();
console.log(child.prototype.name);
console.log(child_example.sex);//undefained
console.log(child_example.name);//'ltp'
//缺陷:子类的实例对象和子类无法访问父类原型中的属性和方法
复制代码
3、组合继承(类式继承和构造函数继承结合)
function parent(){
this.name = 'ltp';
}
parent.prototype = {
age: 11
}
function child(){
parent.call(this);
}
child.prototype = new parent();
//弥补了构造函数继承和类式继承的缺点复制代码
4、寄生式继承
let origin = {};
function inherit(origin){
function F(){}
//方法借用
F.prototype = origin;
return new F();
}
let parent = inherit(origin);复制代码
5、组合寄生
function interit(target,origin){
function F(){}
F.prototype = new origin();
F.constractor = target;
target.prototype = new F();
}
复制代码
6、ES6继承
class A {
constructor(name){
this.name = name;
}
}
class B extends A {
constructor(sex,name){
super(name);
this.sex = sex;
this.method1 = this.method1.bind(this);
}
method1 () {
console.log('已继承');
}
}
let a = new A('ltp');
console.log(a);
let b = new B('ltp','男');
console.log(b);
b.method1();复制代码
super()指向父类,可以向父类实现传参,constructor是构造方法
在ES6继承中,类没有私有变量和私有方法,可通过new实现对类的实例化,extends实现类与类之间的继承