class Character {
constructor(name, health, strength) {
this.name = name;
this.health = health;
this.strength = strength;
this.xp = 0; // XP is always zero for new characters
}
// Return the character description
describe() {
return `${this.name} has ${this.health} health points, ${this
.strength} as strength and ${this.xp} XP points`;
}
}
- 使用 class 关键字创建类,后跟类的名称
- 与对象字面量相反,类中的元素之间没有分隔标点
- 一个类只能包含方法,例如 describe(),不能包含数据属性
- 与对象字面量一样,
this
关键字由 JavaScript 在方法内自动设置,表示调用该方法的对象。 - 可以将一个名为的特殊方法
constructor()
添加到类定义中。它在对象创建期间被调用,通常用于为其提供数据属性。
使用类创建一个对象
使用 new 操作符,调用类构造函数 constructor 来初始化新创建的对象,创建的对象可以访问类中的属性
class Character {
constructor(name, health, strength) {
this.name = name;
this.health = health;
this.strength = strength;
this.xp = 0; // XP is always zero for new characters
}
// Return the character description
describe() {
return `${this.name} has ${this.health} health points, ${this
.strength} as strength and ${this.xp} XP points`;
}
}
const aurora = new Character("Aurora", 150, 25);
const glacius = new Character("Glacius", 130, 30);
// Aurora is harmed by an arrow
aurora.health -= 20;
// Aurora gains a strength necklace
aurora.strength += 10;
// Aurora learns a new skill
aurora.xp += 15;
console.log(aurora.describe());
console.log(glacius.describe());
规范用法如下:
class MyClass {
constructor(param1, param2, ...) {
this.property1 = param1;
this.property2 = param2;
// ...
}
method1(/* ... */) {
// ...
}
method2(/* ... */) {
// ...
}
// ...
}
const myObject = new MyClass(arg1, arg2, ...);
myObject.method1(/* ... */);
// ...