JS 中的 class 类的基本使用

JS 中的class类的基本使用

1. 基本使用 class的基本语法
  1. 使用class关键字定义一个类,本质上是一个function,可以看做一个语法糖,定义了同一组对象(又称为实例)共有的属性和方法
  2. 构造函数的prototype属性也是存在的,实际上所有的方法都是绑定在prototype上面
  3. 在类的实例上调用方法就是在原型上的方法
  4. constructor方法是类的默认方法,通过new生成实例对象的时候就会被调用,一个类必须有constructor方法,如果没有显式定义,一个空的constructor就会被创建
  5. 类里面共有的属性和方法必须要添加this使用
  6. constructor 里面的 this 指向的是创建的实例对象
    class Person {
    	constructor(x,y){
    		// constructor 里面的this 指向的是创建的实例对象
    		this.x = x
    		this.y = y
    	}
    	sum(){
    		console.log(this.x + this.y)	
    	}
    }
    const user = new Person(5,5)
    user.sum() // 10
    

2. 类的继承(extendssuper关键字)

  1. 使用extends关键字可以继承父类的方法,但是如果子类和父类中都存在同一个方法,会采取就近原则,调用子类的方法
    class Father {
    	star(){
    		console.log("Father 中的 star 的方法")
    	}
    	sing() {
    		console.log("Father 中的 sing 方法")
    	}
    }
    class Son extends Father{
    	sing() {
    		console.log("Son 中的 sing 方法")
    	}
    }
    const user = new Son()
    user.star()  // Father 中的 star 的方法
    user.sing() // Son 中的 sing 方法
    
  2. 如果想要传递参数需要使用super关键字,注意使用super关键字的时候必须写在子类的this之前调用
    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){
    		super(x,y)
    		this.x = x
    		this.y = y
    	}
    }
    const user = new Son(5,5)
    user.sum() // 10
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值