前言
总结一下类的实例和静态的字段和方法,附上代码对比。
1、字段
类字段是保存信息的变量,字段可以附加到两个实体:一是类实例上的字段;二是类本身的字段(静态字段)
实例字段:
class User {
constructor(name) {
this.name = name;
}
}
const user = new User('前端车站');
user.name; // => '前端车站'
静态字段:
class User {
static TYPE_ADMIN = 'admin';
static TYPE_REGULAR = 'regular';
constructor(name, type) {
this.name = name;
this.type = type;
}
}
const admin = new User('前端车站', User.TYPE_ADMIN);
admin.type === User.TYPE_ADMIN; // => true
2、方法
字段保存数据,但是修改数据的能力是由属于类的一部分的特殊功能实现的:方法。
实例方法
实例方法可以访问和修改实例数据。实例方法可以调用其他实例方法,也可以调用任何静态方法。
class User {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
const user = new User('前端车站');
user.getName(); // => '前端车站'
静态方法
静态方法是直接附加到类的函数,它们持有与类相关的逻辑,而不是类的实例。使用静态方法时,有两个简单的规则:一是静态方法可以访问静态字段;二是静态方法不能访问实例字段。
class User {
constructor(name) {
this.name = name;
}
static isStatic() {
return this.name;
}
notStatic(){
return this.name;
}
static sum(a, b){
return a + b;
}
}
const user = new User('前端车站');
User.isStatic(); // => "User"
user.notStatic(); // => "前端车站"
User.sum(2, 3); // => 5