es6中的class与继承 (二 )
ES5中的继承 (组合继承:原型链继承 + 借用构造函数)
一、原型链继承:
父类的实例作为子类的原型
function Persion(name,age){
this.name=name;
this.age=age;
this.say=function(){
console.log(`${this.name} ${this.age}`);
}
}
Persion.prototype.test=function(){
console.log("我是原型上的方法");
}
function Women(){
this.sex='女'
}
Women.prototype=new Persion('kity',18);
var one=new Women('tom',20);
one.say();
one.test();
====================================================
二、借用构造函数继承:
在子类内,使用call()调用父类方法,并将父类的this修改为子类的this.相当于是把父类的实例属性复制了一份放到子类的函数内.
function Persion(name,age){
this.name=name;
this.age=age;
this.say=function(){
console.log(`${this.name} ${this.age}`);
}
}
Persion.prototype.test=function(){
console.log("我是原型上的方法");
}
function Women(){
Persion.call(this);
this.name="child";
this.age=18;
}
var one=new Women();
one.say();
one.test();
====================================================
三、 组合继承:
既能调用父类实例属性,又能调用父类原型属性
function Persion(name,age){
this.name=name;
this.age=age;
this.say=function(){
console.log(`${this.name} ${this.age}`);
}
}
Persion.prototype.test=function(){
console.log("我是原型上的方法");
}
function Women(name,age,sex){
Persion.call(this,name,age);
this.sex=sex
}
Women.prototype=new Persion();
var c=new Women('tom',20,'女');
c.say();
c.test();
====================================================
ES6中的 class继承
一、父类(基类)
二、子类
三、extends 关键字
class People{
constructor(name='wang',age='27'){
this.name = name;
this.age = age;
}
eat(){
console.log(`${this.name} ${this.age} eat food`)
}
}
class Woman extends People{
constructor(name = 'ren',age = '27'){
super(name, age);
}
eat(){
super.eat()
}
}
let wonmanObj=new Woman('xiaoxiami');
wonmanObj.eat();
====================================================