灏天阁

· Yin灏

类的定义和继承

class RadiusClass {
  constructor(r) {
    this.r = r;
  }
  circumference(r = this.r) {
    return 2 * Math.PI * r;
  }
  circle_area(r = this.r) {
    return Math.PI * r * r;
  }
}

class Cylinder extends RadiusClass {
  constructor(r, h) {
    super(r);
    this.r = r;
    this.h = h;
  }
  volume(r = this.r, h = this.h) {
    return super.circle_area(r) * h;
  }
  surface_area(r = this.r, h = this.h) {
    return 2 * super.circle_area(r) + super.circumference(r) * h;
  }
}

let rc01 = new RadiusClass(10);
console.log(rc01.circumference()); // 62.83185307179586
console.log(rc01.circumference(15)); // 94.24777960769379

let c01 = new Cylinder(20, 30);
console.log(c01.volume()); // 37699.11184307752
console.log(c01.surface_area()); // 6283.185307179587

类的静态成员

  • 关键字 static 定义的属性或方法。

  • 调用静态属性不用实例化类,即可调用。

class Cubic {
  constructor(l, w, h) {
    this.length = l;
    this.width = w;
    this.height = h;
  }
  volume(l = this.length, w = this.width, h = this.height) {
    return l * w * h;
  }
  surface_area(l = this.length, w = this.width, h = this.height) {
    return 2 * (l * w + w * h + h * l);
  }
  static about() {
    console.log('This class is about calculation of.');
  }
}

let c01 = new Cubic(15, 23, 37);
console.log(c01.volume()); // 12765
console.log(c01.volume(10, 20, 30)); // 6000

console.log(c01.surface_area()); // 3502
console.log(c01.surface_area(10, 20, 30)); // 2200

Cubic.about(); // This class is about calculation of.
// c01.about(); error

类的设置器和取得器

class Person {
  constructor(name="?", age="?", gender="?", department="?") {
    this._name = name;
    this._age = age;
    this._gender = gender;
    this._department = department;
  }
  set name(name) {
    this._name = name;
    console.log('Name is edited!');
  }
  get name() {
    console.log('Name is got!');
    return this._name;
  }
}

let p01 = new Person();
console.log(p01.name);
/*
  Name is got!
  ?
*/

p01.name = 'Jasper';
console.log(p01.name);
console.log(p01._name);

/*
  Name is edited!
  Name is got!
  Jasper
  Jasper
*/

- Book Lists -