prototype的基本用法

50 阅读1分钟
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 创建一个函数
      function User(name, age, sex) {
        this.name = name; /* 等号表示赋值 */
        this.age = age;
        this.sex = sex;
      }
      //   构造一个函数
      var newfun = new User("小红", 15, "男");

      //   为创建的函数添加一个方法,不要写在上面
      // 用prototype
      User.prototype.fangfa = function () {
        console.log(
          "大家好,我叫" +
            this.name +
            ",今年" +
            this.age +
            "岁,是个" +
            this.sex +
            "生"
        );
      };

      //   console.log(newfun);
      // 调用添加的方法
      newfun.fangfa();
    </script>
  </body>
</html>