实例方法与静态方法
2019-07-02 本文已影响0人
SingleDiego
实例方法(Instance Method)顾名思义就是只能在实例对象中运行的方法。
class Circle {
constructor(radius) {
this.radius = radius;
};
draw() {
console.log('draw');
};
}
比如例子中的 draw()
,只能这样调用:
const c = new Circle(1)
c.draw()
而静态方法(Static Method)是类的方法,不针对特定对象。
我们使用 static
关键字声明静态方法:
class Circle {
constructor(radius) {
this.radius = radius;
};
// 实例方法
draw() {
console.log('draw');
};
// 静态方法
static parse() {
console.log('parse')
}
}
调用静态方法不需要创建实例,直接类名+方法名即可:
Circle.parse()