JS-ES6 类

JS-ES6 类

1. 如何定义一个类?

class Star{ 
} //定义了一个叫Star的类
let you = new Star(); // 实例化了一个Star类,并赋值给you

2. 类中的函数

构造函数:在创建类的实例的时候会自动执行的函数

class Star{
  constrcutor(name,age){
    // 这里的this是指向new出来的实例
    this.name = name;
    this.age = age;
    console.log(this.name + "创建成功了!")
  }
}
let person = new Star('handsome')
// 执行结果为 handsome创建成功

普通函数

class Star{
  constrcutor(name,age){
    // 这里的this是指向new出来的实例
    this.name = name;
    this.age = age;
  }
  // 定义一个方法
  sayHi(){
    console.log("你好鸭")
  }
}
let person = new Star('Bob')
// 使用该方法
person.sayHi()

3.类的继承

关键字extends

class Son extends Father{
  // 完全继承父类
}

子类调用父类

  1. 子类将数据传给父类
// 错误分析
class Father {
    constructor(x, y) {
        this.x = x
        this.y = y
    }
    sum() {
        console.log(this.x + this.y);
    }
}

class Son extends Father{
  constructor(x,y){
    this.x = x
    this.y = y
  }
}
let son1 = new Son(2,3)
// 现在我要在子类里调用这个sum方法,但是并没有把x,y 传给父类,所以调用不了
son1.sum()

//正确示范 
class Father {
    constructor(x, y) {
        this.x = x
        this.y = y
    }
    sum() {
        console.log(this.x + this.y);
    }
}

class Son extends Father {
    constructor(x, y) {
      // 在将x,y赋值给实例的属性前,先用 super方法 把x,y传给父类,这样就可以调用父类的方法
        super(x, y)
        this.x = x
        this.y = y
    }
    sub() {
        console.log(this.x - this.y);
    }
}
let son2 = new Son(2,3)
son2.sum()
// 输出5
  1. 子类调用父类的函数

    子类中的函数遵循就近原则

    1. 子类的实例调用一个方法,先看子类中是不是有该方法,若有则直接调用
      1. 若没有,则在父类中查找这个方法
class Father {
    constructor(x, y) {
        this.x = x
        this.y = y
    }
    sum() {
        console.log(this.x + this.y);
    }
  	say(){
      console.log('你好鸭!')
    }
}

class Son extends Father {
    constructor(x, y) {
        super(x, y)
        this.x = x
        this.y = y
    }
    sub() {
        console.log(this.x - this.y);
    }
  	say(){
			super.say()
    }
}

ES6 类 注意事项

  1. ES6里面的类没有变量提升,所以必须先实例化再使用
  2. 公用的属性必须 + this 否则类中找不到该属性
  3. 类中this的指向问题
    1. constructor 里面的this指向 创建的实例对象
    2. 方法里面的this指向这个方法的调用者
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值