ES5 和 ES6 在类和继承的不一样,举例以下:函数
ES5 的类和继承: function Person(name){ this.name = name; } Person.prototype.showName = function(){ return this.name; }; var ops = new Person('娃哈哈'); console.log(ops.showName()); // 娃哈哈
ES6 的类和继承: class Person{ // Person类 它也是一个函数 constructor(name){ // 构造函数 this.name = name; } showName(){ return this.name; } } var p1 = new Person('娃哈哈'); console.log(p1.showName()); // 娃哈哈
Class 能够经过 extends 关键字实现继承,这比 ES5 的经过修改原型链实现继承,要清晰和方便不少,举例以下:学习
ES5 以前的写法: function Person(name){ // 父类 this.name = name; } Person.prototype.showName = function(){ return this.name; }; function SubPerson(name,job){ // 子类 Person.call(this,name); // 子类继承父类的属性 须要将this指向父类中的name this.job = job; // job是子类本身的属性 } SubPerson.prototype = new Person(); // 子类继承父类的方法 var p1 = new SubPerson('娃哈哈'); console.log(p1.name); // 娃哈哈 // console.log(p1.showName()); // 娃哈哈
ES6 有Class类以后的写法: class Person{ constructor(name){ this.name = name; } showName(){ return this.name; } } class SubPerson extends Person{ constructor(name,job){ super(name); // 指向父类的构造函数 this.job = job; } showJob(){ return this.job; } } var p1 = new SubPerson('娃哈哈','喜洋洋'); console.log(p1.name); // 娃哈哈 // console.log(p1.showName()); // 娃哈哈 // console.log(p1.job); // 喜洋洋
estends 就是继承的意思,super 就是指向父类的构造函数,指代了整个prototype对象或者_proto_指针指向的对象。this
super.showName