es6类的用法

2019-11-21  本文已影响0人  Wrestle_Mania
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();
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);

直接在对象上添加属性,类似于静态属性

上一篇 下一篇

猜你喜欢

热点阅读