当前位置: 首页 > 工具软件 > Classing{js} > 使用案例 >

JS 中的 class 类的基本使用

通正平
2023-12-01

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
    
 类似资料: