这次给大家带来的是es6 javascript中类的静态方法,属性与实例属性怎么使用,这篇文章就给大家好好分析一下。
类相当于实例的原型, 所有在类中定义的方法, 都会被实例继承。 如果在一个方法前, 加上static关键字, 就表示该方法不会被实例继承, 而是直接通过类来调用, 这就称为“ 静态方法”。
class Foo {
static classMethod() {
return 'hello';
}
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function上面代码中, Foo类的classMethod方法前有static关键字, 表明该方法是一个静态方法, 可以直接在Foo类上调用( Foo.classMethod()), 而不是在Foo类的实例上调用。 如果在实例上调用静态方法, 会抛出一个错误, 表示不存在该方法。
父类的静态方法, 可以被子类继承。
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();
相信看了以上介绍你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
立即学习“Java免费学习笔记(深入)”;
相关阅读:
以上就是ES6 javascript中类的静态方法,属性与实例属性怎么使用的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号