JavaScript高级(1)

什么是对象?

什么是面对对象?

面向对象与面向过程: 

面向过程的体现

<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>
    // 面向过程创建对象
    // 1.定义学生信息
    var stu1 = {
      name:'张三',
      age:18,
      sex:"男"
    }
    var stu2 = {
      name:'李四',
      age:20,
      sex:"女"
    }
    // 2.定义方法
    // 处理学生的年龄
    function printAge1(){
      console.log(stu1.name+"   "+stu1.age);
    }
     // 处理学生的年龄
     function printAge2(){
      console.log(stu2.name+"   "+stu2.age);
    }
    // 3.调用
    printAge1()
    printAge2()
  </script>
</body>
</html>

面向对象的基本体现

<!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>
    // 1.创建学生类
    function Student(name, score) {
      // 将传进来的值赋值给Student类中的属性
      this.name = name
      this.score = score
    }

    // 2.在原型上添加学生的方法
    // Student.prototype 学生类的原型
    Student.prototype.printScore = function () {
      console.log(this.name + '   ' + this.score);
    }
    Student.prototype.printName = function () {
      console.log(this.name);
    }
    // 3.创建学生的对象 (创建实例)
    // 我们在使用new的时候 new的是Student类的构造方法
    var s1 = new Student('张三',80)
    var s2 = new Student('李四',90)
    // 4.通过学生的对象调用方法
    s1.printScore()
    s2.printScore()
    console.log(s1);

    // 在原型上包含我们自己定义的方法 printScore
    // 还自带一个构造方法 constructor


  </script>
</body>

</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值