js— static关键字用法详解

在 JavaScript 中,static 关键字用于类中定义静态属性和静态方法。这是在 ECMAScript 2015 (ES6) 引入类概念时一同引入的特性。

静态属性

  • 属于类,类调用,而不是实例对象
  • 在ES6中,静态属性并不直接支持,但可以通过在类外部为类添加属性来模拟
  • 在ES2020(或ES11)中,引入了static字段提案,允许直接在类定义中定义静态属性
ES6版本(模拟静态属性):
class MyClass {
}
//不能直接类中用static关键字,但是可以外部用类来添加属性的方式实现
MyClass.staticProperty = "I am a static property";

console.log(MyClass.staticProperty); // 输出 "I am a static property"
ES2020及之后版本(直接定义静态属性):
class MyClass {  
  static myStaticProperty = 'This is a static property';  
}  
//可以直接在类中用static关键字定义属性,(类属性)
console.log(MyClass.myStaticProperty); // 输出: "This is a static property"

静态方法

  • 属于类,类调用,而不是实例对象
class MyClass {
  static staticMethod() {
    return "I am a static method";
  }
}
console.log(MyClass.staticMethod()); // 输出 "I am a static method"

静态方法可以通过 this 关键字调用同一个类中的其他静态方法:

class MyClass {
  static firstStaticMethod() {
    return this.secondStaticMethod();
  }

  static secondStaticMethod() {
    return "Called from second static method";
  }
}

console.log(MyClass.firstStaticMethod()); // 输出 "Called from second static method"

总结

  • 不管是静态属性还是方法,都属于类,类调用
  • 静态方法可以通过 this 关键字调用同一个类中的其他静态方法,这里的this指的是类的上下文,而不是对象的上下文,但是普通方法中不可以通过this掉用静态方法例如:
class MyClass {

  static staticMethod() {
    console.log("This is a static method.");
  }
  //该方法是实例方法,里面的this是实例的上下文
  //所以不能通过this掉用staticMethod
  instanceMethod() {
    // 只能通过类名调用静态方法
    MyClass.staticMethod();

    // 或者通过构造函数调用静态方法
    if (this.constructor.staticMethod) {
      this.constructor.staticMethod();
    }
  }
}
const myInstance = new MyClass();
myInstance.instanceMethod(); // 这将会输出 "This is a static method."
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晨枫阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值