9. Class

构造函数尽可能使用 Class 的形式

  1. // 例子 9-1
  2.  
  3. class Foo {
  4. static bar () {
  5. this.baz();
  6. }
  7. static baz () {
  8. console.log('hello');
  9. }
  10. baz () {
  11. console.log('world');
  12. }
  13. }
  14.  
  15. Foo.bar(); // hello
  1. // 例子 9-2
  2.  
  3. class Shape {
  4. constructor(width, height) {
  5. this._width = width;
  6. this._height = height;
  7. }
  8. get area() {
  9. return this._width * this._height;
  10. }
  11. }
  12.  
  13. const square = new Shape(10, 10);
  14. console.log(square.area); // 100
  15. console.log(square._width); // 10