JavaScript 类(class)实例和静态的字段和方法

前言

总结一下类的实例和静态的字段和方法,附上代码对比。

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值