543 class类的私有属性

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>私有属性</title>
</head>

<body>
  <script>
    class Person {
      // 公有属性
      name;

      // 私有属性,前面加#
      #age;
      #weight;

      // 构造方法
      constructor(name, age, weight) {
        this.name = name;
        this.#age = age;
        this.#weight = weight;
      }

      intro() {
        console.log(this.name); // 晓红
        console.log(this.#age); // 18
        console.log(this.#weight); // 45 
      }
    }

    // 实例化
    const girl = new Person('晓红', 18, '45kg');

    // 类外面不能直接访问类的私有属性,只能在类里面才做私有属性
    console.log(girl.name); // 晓红
    // console.log(girl.#age); // 报错
    // console.log(girl.#weight);

    girl.intro();
  </script>
</body>

</html>
原文地址:https://www.cnblogs.com/jianjie/p/13680157.html