JS面向对象(一)类与对象写法

注释很详细,直接上代码

新增内容:
1. 类的基本用法
2. 类的继承用法
3. 类的this指向问题

项目结构:

仅一个文件

源码:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>点击</button>
  </body>
  <script>
    //基础用法
    //-------------------------------------------------------🌹🌹🌹

    //对象Person -类名一般首字母大写
    class Person {
      constructor(name, age) {
        //构造函数
        this.name = name;
        this.age = age;
      }

      say() {
        //say方法(无参)
        alert(this.name + "今年" + this.age + "岁了");
      }
      worship(name) {
        //worship方法(有参)
        alert(this.name + "膜拜膜拜" + name);
      }
    }

    /*
    let p = new Person("张三", 20); //实例化新对象
    p.say(); //调用say方法
    p.worship("眨眼睛一号");//调用worship方法
    */

    //继承用法
    //-------------------------------------------------------🌹🌹🌹

    class Student extends Person {
      //继承Person类
      constructor(name, age, school) {
        //构造函数
        super(name, age); //调用父类的构造函数
        this.school = school;
      }
      say() {
        //重载say方法,如无,则默认调用父类的say方法
        alert(this.name + "今年" + this.age + "岁了,学校是" + this.school);
      }

      worship(name) {
        //super调用父类的worship方法
        super.worship(name);
      }

      yyds(name) {
        //子类扩展自身的方法
        alert(name + "yyds!");
      }
    }

    /*
    let s = new Student("李四", 18, "B站大学");
    s.say();
    s.worship("眨眼睛二号");
    s.yyds("眨眼睛");
    */


    //类中的this指向
    //-------------------------------------------------------🌹🌹🌹
    let that;
    class Star {
      constructor(uname, age) {
        // constructor 里面的this指向的是创建的实例对象,储存起来可以使一些嵌套了的方法可以使用该对象的this
        that = this;
        this.uname = uname;
        this.age = age;
        this.btn = document.querySelector("button");
        this.btn.onclick = this.sing;
      }
      sing() {
        // 这个sing方法里面的this 指向的是 btn 这个按钮,因为这个按钮调用了这个函数
        console.log(this);

        console.log(that); // that里面存储的是constructor里面的this
      }
    }

    var ldh = new Star("刘德华");
  </script>
</html>

效果演示:

为了更清晰进行了注释,小友按着分类解开注释一个个看吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码对我眨眼睛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值