ES6类class和对象

类:抽取了对象的公共部分,泛指某一大类(class)

对象特指某一个,通过类实例化一个具体的对象

面向对象的思维特点

1.抽取(抽象)对象共用的属性和行为组织(封装)成一个类(模版)

2.对类进行实例化,获取类的对象

类和对象的使用

  <script>
    // 创建一个类,泛指某一大类
    class Father {
      constructor(uname,age) { //constructor定义构造函数,传参
        this.uname = uname 
        this.age = age 
      }
    }
    // 利用类创建对象
    let son = new Father('lisi',18)
    let zs = new Father('zhangsan',18)
    console.log(son);
    console.log(zs);
  </script>

类名习惯性首字母大写

类里的constructor函数,可以接受传递过来的参数,同时返回实例

在class可设置一些公共的方法

    class Father {
      constructor(uname,age) {
        this.uname = uname 
        this.age = age 
      }
      say() {
        console.log( '我' + this.uname +'是法外狂徒');
        // console.log(this.uname);
      }
    }
    // 利用类创建对象
    let son = new Father('lisi',18)
    let zs = new Father('zhangsan',18)
    console.log(son);
    console.log(zs);
    son.say()
    zs.say()

设置公共类设置方法,不需要逗号隔开,不需要写function

类的继承

  <script>
    class Father {
      constructor(x,y) {
        this.x = x
        this.y = y
      }
      computed() {
        console.log(this.x + this.y);
      }
    }
    class Son extends Father {
      constructor(x,y) {
        super(x,y)
      }
    }
    let son = new Son(1,2)
    let son1 = new Son(11,22)
    // console.log(son);
    son.computed()
    son1.computed()
  </script>

子类构造函数继承父类构造函数要用到super引用父类构造函数里的函数(方法)

继承中的属性或者方法查找原则:就近原则

  <script>
    class Father {
      constructor(x,y) {
        this.x = x
        this.y = y
      }
      num() {
        console.log(this.x + this.y);
      }
    }
    class Son extends Father {
      constructor(x,y) {
        super(x,y)
        this.x = x
        this.y = y
      }
      decurrent() {
        console.log(this.x - this.y);
      }
    }
    let son = new Son(8,2)
    son.decurrent()
    son.num()
  </script>

子类构造函数继承父类方法,同时自身添加一个方法,用super()继承父类函数方法时,必须把super放在this的前面

  <script>
    class Father {
      constructor(x,y) {
        this.x = x
        this.y = y
        this.btn=document.querySelector('button')
        this.btn.onclick=this.slove  //不能加括号,加括号是直接执行
      }
      slove() {
        console.log('1111111111111');
      }
    }
    let son = new Father()
    // son.slove()
  </script>

在es6中类没有变量提升,所以必须先定义类,才能通过类实例化

在类里面的共有的属性和方法一定要加this使用

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值