静态方法 使用static关键字修饰的方法,叫静态方法
静态方法的好处就是不用生成类的实例就可以直接调用。
static方法修饰的成员不再属于某个对象,而是属于它所在的类。只需要通过其类名就可以访问,不需要再消耗资源反复创建对象。
在类第一次加载的时候,static就已经在内存中了,直到程序结束后,该内存才会释放。
# 静态方法的特点
1.只能通过类名调用
2.不能再静态方法中使用普通方法
3.静态方法中this指调用静态方法的类
4.静态方法是可以被继承的
<script>
/*
1、使用static关键字修饰的方法,叫静态方法
a、只能通过类名去调用
b、静态方法中的this指向class类
*/
class Http{
static baseUrl = "https://www.yuque.com"
static request(){
console.log(this)
console.log("request")
}
}
var h = new Http();
Http.request()
h.request()
</script>
静态方法中的this
静态方法中的this指向类。
class Student{
static init(){
this.say();
Student.say();
}
static say(){
console.log("hello world")
}
}
Student.init();
静态属性
使用static关键字修饰的变量,叫静态属性。只能通过类名来调用
<script>
/*
1、使用static关键字修饰的变量,叫静态属性。只能通过类名来调用
2、使用static关键字修饰的方法,叫静态方法
*/
class Http{
static baseUrl = "https://www.yuque.com"
static request(){
console.log(this)
console.log("request")
}
}
var h = new Http();
console.log(Http.baseUrl)
console.log(h.baseUrl)
</script>