九门宁生

导航

js演示面向对象

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <script>
    // 打印学生的成绩表
    // 
    // 
    // 1 面向过程的方式
    // // 1.1 记录学生的成绩
    // var stu1 = {name: 'zs', subject: '语文', score: 90};
    // var stu2 = {name: 'ls', subject: '语文', score: 80};
    // // 1.2 打印学生的成绩
    // console.log(stu1.name, stu1.subject, stu1.score);
    // console.log(stu2.name, stu2.subject, stu2.score);


    //2 面向对象的方式
    // 创建一个模板,用于创建对象(实例instance)
    // 在JavaScript中创建对象的模板是构造函数
    // 而在其他语言中创建对象的模板是类
    function Student(name, subject, score) {
      this.name = name;
      this.subject = subject;
      this.score = score;

      this.printScore = function () {
        console.log(this.name, this.subject, this.score);
      }
    } 

    var stu1 = new Student('zs', '语文', 90);
    var stu2 = new Student('ls', '语文', 80);

    stu1.printScore();
    stu2.printScore();
  </script>
</body>
</html>

 

posted on 2019-08-29 14:37  九门宁生  阅读(174)  评论(0编辑  收藏  举报