ES6 Class类
- class 本质是
function
- class
不可重复声明
- 类定义
不会提升
,这意味着必须在访问前对类进行定义,否则会报错 - 类中方法不需要加
function
关键字 - 方法中不能用
逗号
类定义
// 匿名类
let Example = class {
constructor(a) {
this.a = a;
}
}
// 命名类
let Example = class Example {
constructor(a) {
this.a = a;
}
}
类声明
class Example {
constructor(a) {
this.a = a;
}
}
注意要点:不可重复声明。
class Example{}
class Example{}
// Uncaught SyntaxError: Identifier 'Example' has already been
// declared
let Example1 = class{}
class Example{}
// Uncaught SyntaxError: Identifier 'Example' has already been
// declared
类的主体
Example.prototype={
//methods
}
//添加方法
Object.assign(Example.prototype,{
//methods
})
静态属性
class Example {
// 新提案
static a = 2;
}
// 目前可行写法
Example.b = 2;
公开属性
class Example{}
Example.prototype.a = 2;
constructor 方法
constructor 方法是类的默认方法,创建类的实例化对象时被调用。
class Example{
constructor(){
console.log('我是constructor');
}
}
new Example(); // 我是constructor
静态方法
class Example{
static sum(a, b) {
console.log(a+b);
}
}
Example.sum(1, 2); // 3
原型方法
class Example{
static sum(a, b) {
console.log(a+b);
}
}
Example.sum(1, 2); // 3
实例方法
class Example {
constructor() {
this.sum = (a, b) => {
console.log(a + b);
}
}
}
类的实例化
class 的实例化必须通过 new 关键字。
class Example {}
let exam1 = Example();
// Class constructor Example cannot be invoked without 'new'
共享原型对象
class Example {
constructor(a, b) {
this.a = a;
this.b = b;
console.log('Example');
}
sum() {
return this.a + this.b;
}
}
let exam1 = new Example(2, 1);
let exam2 = new Example(3, 1);
// __proto__ 已废弃,不建议使用
// console.log(exam1.__proto__ == exam2.__proto__);
console.log(Object.getPrototypeOf(exam1) === Object.getPrototypeOf(exam2));// true
Object.getPrototypeOf(exam1).sub = function() {
return this.a - this.b;
}
console.log(exam1.sub()); // 1
console.log(exam2.sub()); // 2
封装与继承
getter / setter
- getter 不可单独出现
- getter 与 setter 必须同级出现
class Example{
constructor(a, b) {
this.a = a; // 实例化时调用 set 方法
this.b = b;
}
get a(){
console.log('getter');
return 99;
}
set a(user){
console.log('setter');
this.age = user;
}
}
let exam = new Example(10,20);
console.log(exam1);
extends
通过 extends 实现类的继承。
class Child extends Father { ... }
super
- 子类 constructor 方法中必须有 super ,且必须出现在 this 之前。
- 调用父类构造函数,只能出现在子类的构造函数。
- 调用父类方法, super 作为对象,在普通方法中,指向父类的原型对象,在静态方法中,指向父类
class Father {
constructor() {}
}
class Child extends Father {
constructor() {}
// or
// constructor(a) {
// this.a = a;
// super();
// }
}
let test = new Child(); // Uncaught ReferenceError: Must call super
// constructor in derived class before accessing 'this' or returning
// from derived constructor