- 基本写法
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
getName() {
console.log(this.name);
}
setName(name) {
this.name = name;
}
}
const person = new Person("JonSnow", 21);
console.log(person.name);
person.setName("Cercei");
person.getName();
- 通过extends与super实现继承
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
getInfo() {
console.log(`${this.name}--${this.age}`);
}
}
class Student extends Person {
constructor(name, age, sex) {
super(name, age);
this.sex = sex;
}
work() {
console.log("code");
}
}
const student = new Student("JonSnow", 21, "男");
console.log(student.name); //JonSnow
student.getInfo(); //JonSnow--21
console.log(student.sex); //男
student.work(); //code
- 静态方法
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
run() {
console.log("run");
}
static work() {
console.log("work");
}
}
const person = new Person("JonSnow", 21);
person.run();
Person.work();
比较尴尬的是,在静态方法中是没法获取到this的
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
run() {
console.log("run");
}
static work() {
console.log("work");
}
}
Person.sex = "男";
const person = new Person("JonSnow", 21);
person.run();
Person.work();
console.log(Person.sex);
直接在对象上添加属性,类似于静态属性
网友评论