ES6中实现类的继承语法进行了优化,很类似于Java的语法,下面分别演示下ES5和ES6的两种语法。
- ES 5 语法
prototype和__proto__不熟悉的同学,可以参照如下内容prototype和__proto__。
function Person(name, age) {
this.name = name;
this.age = age;
this.innerFunction = function () {
console.log("innerFunction")
}
}
Person.prototype.show = function () {
console.log(`${this.name},${this.age}`)
}
function Student(name, age, sex) {
Person.call(this,name,age)
this.sex = sex;
}
Student.prototype.__proto__=Person.prototype;
var s1 = new Student('jack', 22, 'boy');
var s2 = new Student('lucy', 21, 'girl');
s1.show() //jack,22
s2.show() //lucy,21
console.log(s1.show===s2.show) //true
- ES6 语法
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
show() {
console.log(this.name, this.age)
}
}
class Student extends Person {
constructor(name, age, sex) {
super(name, age);
this.sex = sex;
}
}
let s1 = new Student('jack', 22, 'boy');
let s2 = new Student('lucy', 21, 'girl');
s1.show() //jack,22
s2.show() //lucy,21
console.log(s1.show === s2.show) //true