网站推广话术,桂林设计单位资质升级网站,c2c代表网站是什么,网页设计与制作张苏中素材类相当于实例的原型#xff0c;所有在类中定义的方法#xff0c;都会被实例继承。如果在一个方法前#xff0c;加上static关键字#xff0c;就表示该方法不会被实例继承#xff0c;而是直接通过类来调用#xff0c;这就称为“静态方法”。
class Foo {static classMetho…类相当于实例的原型所有在类中定义的方法都会被实例继承。如果在一个方法前加上static关键字就表示该方法不会被实例继承而是直接通过类来调用这就称为“静态方法”。
class Foo {static classMethod() {return hello;}
}Foo.classMethod() // hellovar foo new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function上面代码中Foo类的classMethod方法前有static关键字表明该方法是一个静态方法可以直接在Foo类上调用Foo.classMethod()而不是在Foo类的实例上调用。如果在实例上调用静态方法会抛出一个错误表示不存在该方法。
注意如果静态方法包含this关键字这个this指的是类而不是实例。
class Foo {static bar() {this.baz();}static baz() {console.log(hello);}baz() {console.log(world);}
}Foo.bar() // hello上面代码中静态方法bar调用了this.baz这里的this指的是Foo类而不是Foo的实例等同于调用Foo.baz。另外从这个例子还可以看出静态方法可以与非静态方法重名。
父类的静态方法可以被子类继承。
class Foo {static classMethod() {return hello;}
}class Bar extends Foo {
}Bar.classMethod() // hello
上面代码中父类Foo有一个静态方法子类Bar可以调用这个方法。静态方法也是可以从super对象上调用的。class Foo {static classMethod() {return hello;}
}class Bar extends Foo {static classMethod() {return super.classMethod() , too;}
}Bar.classMethod() // hello, too