Class类
在ES6中,class (类)作为对象的模板被引入,可以通过 class 关键字定义类。
class 的本质是 function。
它可以看作一个语法糖,让对象原型的写法更加清晰、更像面向对象编程的语法。
Class类声明
Class类表达式
提升
- 函数声明会提升
- class类不会提升
实例属性和方法
class Rectangle {
// constructor
constructor(height, width) {
//实例属性
this.height = height;
this.width = width;
}
//实例方法
get area() {
return this.calcArea()
}
//实例方法
calcArea() {
return this.height * this.width;
}
}
}
const square = new Rectangle(10, 10);
console.log(square.area);
原型上的属性和方法
function foo(){
//静态属性
this.a='a'
//静态方法
this.state=function(){
console.log(1)
}
}
foo()
decorator
decorator 是一个函数,用来修改类的行为,在代码编译时产生作用。
//一个参数
//第一个参数 target,指向类本身。
function testable(target) {
target.isTestable = true;
}
@testable
class Example {}
Example.isTestable; // true
//多个参数——嵌套实现
function testable(isTestable) {
return function(target) {
target.isTestable=isTestable;
}
}
@testable(true)
class Example {}
Example.isTestable; // true
extends
通过 extends 实现类的继承。
class Child extends Father { ... }
super
子类 constructor 方法中必须有 super ,且必须出现在 this 之前。
防止构造函数的原型上的方法找不到this指向