Skip to content

静态方法 ​

本节目标:理解“静态方法”的核心思路,并能把它用于实际开发或面试表达。 概念:静态方法是指直接通过类名来调用的方法。 声明:静态方法通过在类方法的前面加static关键字来声明。 注意:

静态方法不会被类的实例继承,如果在实例上调用静态方法,会抛出一个错误,表示不存在该方法。

静态方法中的this指的是类,而不是实例。
类中的静态方法可以与非静态方法重名;
class Foo {
    static classMethod() {
        return 'hello';
    }
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function
class Foo {
    static bar() {
        this.baz();
    }
    static baz() {
        console.log('hello');
    }
    baz() {
        console.log('world');
    }
}
Foo.bar() // hello
**继承性:**
父类的静态方法,可以被子类继承。
父类静态方法可以与子类静态方法重名。
class Foo {  static classMethod() {    return 'hello';  }}
class Bar extends Foo {}
Bar.classMethod() // 'hello'
class Foo {  static classMethod() {    return 'hello';  }}
class Bar extends Foo {  static classMethod() {    return super.classMethod() + ', too';  }}
Bar.classMethod() // "hello, too"

本站总访问 — 次