Class类
ES6引入Class(类)的概念,让类的写法更接近传统语言的写法,ES6的类可以看作是语法糖,它的绝大部分功能,ES5都可以做得到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法
对比ES5和ES6创建class的写法
// ================= ES5 start =================
// ES5 -> 构造函数、原型方法、静态属性
// 构造函数
function Person(name, age) {
this.name = name;
this.age = age;
}
// 原型方法
Person.prototype.getName = function() {
return this.name;
}
// 静态属性
Person.info = "Person的静态属性";
const person = new Person("Damao", 18);
console.log(person.getName()); // Damao
console.log(Person.info); // Person的静态属性
// ================= ES5 end =================
// ================= ES6 start =================
// ES6 -> 构造函数、原型方法、静态属性
class Person {
constructor(name, age) { // 构造函数
this.name = name;
this.age = age;
}
getName() { // 原型方法(无需加function)
return this.name;
}
}
// 静态属性
Person.info = "Person的静态属性";
const person = new Person("Damao", 18);
console.log(person.getName()); // Damao
console.log(Person.info); // Person的静态属性
// ================= ES6 end =================
- ES6 class中,用static修饰即为类的静态方法(可以直接用类名访问),即在这个类(构造函数)对象本身上的方法,加上static表示该方法不会被实例继承
class Person {
static classMethod() {
return "this is static method";
}
}
console.log(Person.classMethod()); // this is static method
//
// 静态方法不可以通过实例来即成,即不能通过实例调用,如
let person = new Person();
console.log(person.classMethod()); // TypeError: person.classMethod is not a function
类的继承extends
- Class可以通过extends关键字来实现继承,而ES5则需要通过修改原型链来实现继承
- 对比ES5和ES6继承的写法
// ================= ES5 start =================
// ES5 -> 利用原型让一个引用类型继承另一个引用类型的属性和方法,即让原型对象等于另一个类型的实例
// 原型继承缺点:父类公有和私有属性方法都为子类公有
//
function Person() {
this.name = "Damao";
}
Person.prototype.getName = function() {
return this.name;
}
function SuperPerson() {
this.superName = "Damao2250";
}
// 继承 Person
SuperPerson.prototype = new Person();
SuperPerson.prototype.constructor = SuperPerson;
SuperPerson.prototype.getSuperName = function() {
return this.superName;
}
const superPerson = new SuperPerson();
console.log(superPerson.getName()); // Damao
console.log(superPerson.getSuperName()); // Damao2250
// ================= ES5 end =================
// ================= ES6 start =================
class Person {
constructor(name, age) { // 构造函数
this.name = name;
this.age = age;
}
getName() { // 原型方法(无需加function)
return this.name;
}
}
class SuperPerson extends Person {
constructor(name, age, superName) {
// 在继承的构造函数中,必须调用一次super方法,它表示构造函数的继承;必须在this前调用
// super()是将父类中的this对象继承给子类
super(name,age);
this.superName = superName;
}
superGetName() {
// super 直接调用父级的原型方法
console.log(super.getName());
console.log(this.superName);
}
}
const person = new SuperPerson("Damao", 18, "Damao2250");
console.log(person.getName()); // Damao
console.log(person.superGetName()); // Damao Damao2250
// ================= ES6 end =================