實(shí)例方法(Instance Method)顧名思義就是只能在實(shí)例對(duì)象中運(yùn)行的方法鼎俘。
class Circle {
constructor(radius) {
this.radius = radius;
};
draw() {
console.log('draw');
};
}
比如例子中的 draw()
,只能這樣調(diào)用:
const c = new Circle(1)
c.draw()
而靜態(tài)方法(Static Method)是類的方法做修,不針對(duì)特定對(duì)象。
我們使用 static
關(guān)鍵字聲明靜態(tài)方法:
class Circle {
constructor(radius) {
this.radius = radius;
};
// 實(shí)例方法
draw() {
console.log('draw');
};
// 靜態(tài)方法
static parse() {
console.log('parse')
}
}
調(diào)用靜態(tài)方法不需要?jiǎng)?chuàng)建實(shí)例抡草,直接類名+方法名即可:
Circle.parse()