静态方法 使用static关键字修饰的方法,叫静态方法

静态方法的好处就是不用生成类的实例就可以直接调用。
static方法修饰的成员不再属于某个对象,而是属于它所在的类。只需要通过其类名就可以访问,不需要再消耗资源反复创建对象。
在类第一次加载的时候,static就已经在内存中了,直到程序结束后,该内存才会释放。

  1. # 静态方法的特点
  2. 1.只能通过类名调用
  3. 2.不能再静态方法中使用普通方法
  4. 3.静态方法中this指调用静态方法的类
  5. 4.静态方法是可以被继承的
  1. <script>
  2. /*
  3. 1、使用static关键字修饰的方法,叫静态方法
  4. a、只能通过类名去调用
  5. b、静态方法中的this指向class类
  6. */
  7. class Http{
  8. static baseUrl = "https://www.yuque.com"
  9. static request(){
  10. console.log(this)
  11. console.log("request")
  12. }
  13. }
  14. var h = new Http();
  15. Http.request()
  16. h.request()
  17. </script>

静态方法中的this

静态方法中的this指向类。

  1. class Student{
  2. static init(){
  3. this.say();
  4. Student.say();
  5. }
  6. static say(){
  7. console.log("hello world")
  8. }
  9. }
  10. Student.init();

静态属性

使用static关键字修饰的变量,叫静态属性。只能通过类名来调用

  1. <script>
  2. /*
  3. 1、使用static关键字修饰的变量,叫静态属性。只能通过类名来调用
  4. 2、使用static关键字修饰的方法,叫静态方法
  5. */
  6. class Http{
  7. static baseUrl = "https://www.yuque.com"
  8. static request(){
  9. console.log(this)
  10. console.log("request")
  11. }
  12. }
  13. var h = new Http();
  14. console.log(Http.baseUrl)
  15. console.log(h.baseUrl)
  16. </script>