继承前提---- 继承分为两种:类与类之间的继承,类创造实例对象bash
funtion parent(){
//私有属性
var name ;
//私有方法
var addName = function(){};
//公有属性
this.sex;
//公有方法
this.addSex = function(){};
}
parent.prototype = {
//共有属性(原型属性)
age: 11,
//共有方法
setAge: function(){}
}复制代码
一、类式继承:(类与类之间的继承)函数
function parent(){ this.name = [];
}
parent.prototype = {
age: 12
}
//声明子类
function child(){}
child.prototype = new parent();
//缺陷:
//一、父类的公共属性为引用类型时,子类生成的实例对象之间的属性会相互影响
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]
//二、子类实例没法初始化父类原型中的属性和方法
复制代码
二、构造函数继承:(类与类之间的继承)ui
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'
//缺陷:子类的实例对象和子类没法访问父类原型中的属性和方法
复制代码
三、组合继承(类式继承和构造函数继承结合)this
function parent(){
this.name = 'ltp';
}
parent.prototype = {
age: 11
}
function child(){
parent.call(this);
}
child.prototype = new parent();
//弥补了构造函数继承和类式继承的缺点复制代码
四、寄生式继承spa
let origin = {};
function inherit(origin){
function F(){}
//方法借用
F.prototype = origin;
return new F();
}
let parent = inherit(origin);复制代码
五、组合寄生prototype
function interit(target,origin){
function F(){}
F.prototype = new origin();
F.constractor = target;
target.prototype = new F();
}
复制代码
六、ES6继承code
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实现类与类之间的继承继承