JavaScript之ES6中的class与继承

参考:https://www.imooc.com/article/17389

https://www.cnblogs.com/chenyangsuaige/p/6130737.html

继承可以实现很好的封装,子类直接对父类的方法进行重用,还可以添加自己的属性和方法。

原型对象prototype是类的唯一标识符,类的继承是基于prototype的。

es5中类的继承

//es5 类的继承四部曲
//1、创建父类
function Parent(name){
    this.name = name;
}
Parent.prototype.location = "earth";
Parent.prototype.getName = function(){
    console.log(this.name);
}
//2、创建子类
function Son(name,age){
    Parent.call(this,name);//子类调用父类的构造函数
    this.age = age;
}
//3、创建继承,子类的原型对象是父类的一个实例
Son.prototype = new Parent();//这里Son.prototype._proto_=Parent.prototype,Son.prototype.constructor=Parent
//修正子类的constructor
Son.prototype.constructor = Son;
//4、添加子类成员
Son.prototype.id = 123;
Son.prototype.getAge = function(){
  console.log(this.age);
}

//创建一个实例
var student1 = new Son('asd','11');
student1.getName();//asd,继承自父类的方法
student1.getAge();//11,子类自己的方法

es6中类的继承

//es6中class与继承

//创建父类
class Parent{
    constructor(name){
        this.name = name;
    }//!!!注意,这里没有逗号
    getName(){
        console.log(this.name);
    }
}
//子类继承自父类 class Son extends Parent{ constructor(name,age){ super(name);//super指向父类的实例对象,调用父类的constructor,必须先调用super方法,子类才能使用this this.age = age;//子类继承父类的this对象并修改 } getName(){ super.getName();//调用父类的方法 console.log('son'); } }

注意:

1、es6类中只能定义constructor属性和方法,方法全部定义在类的prototype中,且方法不可枚举;

2、es6中类的constructor属性相当于es5中的构造函数,如果没有定义constructor属性,默认会添加一个空的constructor;

3、es5中,继承是子类先创建自己的实例对象this,然后通过Parent.call(this)或Parent.apply(this)调用父类的方法;es6中,继承是父类先创建自己的实例对象this,然后子类继承父类的this,在子类的constructor中修改this。

posted @ 2018-04-12 17:10  你是海上的烟火  阅读(196)  评论(0编辑  收藏  举报