JS Class 使用以及静态方法的调用

170 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // Person
    class Person {
      // 构造函数
      constructor (name, age) {
        this.name = name
        this.age = age
      }
      // 方法
      sayHello () {
        console.log('我的名字是:'+this.name+',我的年龄是:'+this.age);
      }
    }
    // 创建对象
    const p = new Person('dzm', 18)
    // 调用内部方法
    p.sayHello() // 输出 '我的名字是:dzm,我的年龄是:18'

    // 工具类
    class Utils {
      // 静态方法
      static sayHello () {
        console.log('我的名字是:'+this.name+',我的年龄是:'+this.age);
      }
    }
    // 调用静态方法
    Utils.sayHello() // 输出 '我的名字是:Utils,我的年龄是:undefined'
  </script>
</body>
</html>