美文网首页
class 回顾学习

class 回顾学习

作者: A_dfa4 | 来源:发表于2021-03-03 15:27 被阅读0次

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<script>
  // 常见person类
  class Person {
    // 构造器方法
    constructor (name, age) {
      // 构造器中的this 是 new的类的实例对象
      this.name = name
      this.age = age
    }

    // 一般方法
    eat () {
      console.log("吃吃吃")
    }

    say () {
      // say 方法 放在了哪里  放在了person类的原型上, 给实例使用,this 执行调用的实例对象
      // 通过person 实例调用 say时, say中的this就是 person实例p1
      console.log(`我的 名字是 ${this.name}, 我的年龄是 ${this.age}`)
    }

  }

  // 创建一个person实例对象
  // const p1 = new Person('tom', 22)
  // const p2 = new Person('jerry', 15)
  // p1.say()
  // p2.say()
  // console.log(p1)
  // console.log(p2)
  // p1.say.call({a:11})  // this只想被改变了

  class Student extends Person {
    constructor (name, age, grade) {
      // 实现类继承并且有constructor 构造器时 必须调用super() 继承中需要的参数需在super中传递
      super(name, age)
      this.grade = grade
    }

    // 重写从父类继承的方法
    say () {
      console.log(`我的 名字是 ${this.name}, 我的年龄是 ${this.age} 我的班级是${this.grade}`)
    }

    study () {
      console.log("很努力的学习")
    }
  }

  const s1 = new Student('xiaozhang', 8, '三年级')
  console.log(s1)
  s1.say()
  s1.study()

  /*总结
  * 类中的构造器 不是必须写的, 要对实例进行一些初始化的操作如添加属性时才写,
  * 如果A类继承B类 且 A类中写了构造器 constructor 那么A类构造中必须要调用super
  * 类中定义的方法 都是放在了类的原型对象上
  * */
</script>
</body>
</html>

相关文章

网友评论

      本文标题:class 回顾学习

      本文链接:https://www.haomeiwen.com/subject/xvwqqltx.html