1.4 Class类的静态方法

什么是静态方法

类相当于实例的原型,所有在类中定义的方法都会被实例继承。如果在方法前面加上 static 关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就成为"静态方法"

class MakeFoo{
    static classMethod(){
        console.log('hello');
    }
}
//只能通过类来调用
MakeFoo.classMethod();//hello

//在实例中调用报错未定义
let smallF = new MakeFoo();
smallF.classMethod();// Uncaught TypeError: smallF.classMethod is not a function

上面的例子表明,静态方法只能通过类来调用,实例无法继承,如果在实例上调用静态方法,就会抛出错误,表示该方法不存在。

注意,如果静态方法中包含 this 关键字,这个 this 指向的是类,而不是实例。

class MakeFoo{
    static classMethod(){
        //this 指向类,而不是实例
        this.classWrite();
    }
    static classWrite(){
        console.log("hello world!");
    }
    classWrite(){
        console.log("你好,世界!");
    }
}

MakeFoo.classMethod();// hello world!

上面的代码中,静态方法classMethod 中 调用了 this.classWrite 方法,这里的 this 指向的是MakeFoo类,而不是MakeFoo的实例,等同于调用了MakeFoo. classWrite。另外,从这个例子可以看出,静态方法可以与非静态方法重名。

父类的静态方法可以被子类继承

class MakeFoo{
    static classWrite(){
        console.log("hello world!");
    }
}

class SmallFoo extends MakeFoo{

}

SmallFoo.classWrite();// hello world!

上面的代码中,父类 MakeFoo有一个静态方法,子类 SmallFoo可以调用这个方法。

静态方法也可以从super对象上来调用

class MakeFoo{
    static classWrite(){
        return '你好,'
    }
}

class SmallFoo extends MakeFoo{
    static myWrite(){
        console.log(super.classWrite() + 'world')
    }
}

SmallFoo.myWrite();// 你好,world

类的静态属性

类的静态属性指的是Class 类本身的属性,即Class.propName,而不是定义在实例对象 this上的属性。

class Foo{}
Foo.method = "GET";
console.log(Foo.method);//GET

上面的写法定义了一个新静态属性 method ,目前只有这种写法可行,因为ES6明确规定,Class 内部只有静态方法,没有静态属性。新提案提供了一个解决方法,就是在实例属性的前面,加上 static 关键字。

class Foo{
    static myStaticProp = 41
    funs1(){
        console.log(Foo.myStaticProp);
    }
}
let f1 = new Foo();
f1.funs1();//41
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值