ES6 - 类的静态方法和静态属性

一、静态方法

类的所有方法都定义在类的prototype属性上面,所有类中定义的方法都会被实例继承,如果在类方法前面加上static关键字就不会被实例继承了。
静态方法是直接通过类名来调用。

class Person{
	constructor(name="xf",age){
		this.name = name;
		this.age = age;
	}
	static say(){
		console.log("这是静态方法");
	}
}
//通过类名来调用静态方法
Person.say(); // 这是静态方法

静态方法也可以从super继承调用 ,子类调用父类的static方法也只能在静态函数中调用。

class Person{
	constructor(name="xf",age){
		this.name = name;
		this.age = age;
	}
	static say(){
		console.log("这是静态方法");
	}
}
//通过类名来调用静态方法
Person.say(); // 这是静态方法

//子类继承父类
class Child extends Person{
	//这里没写构造函数,那么就是默认有了空的构造函数并且默认调用了super()	
	static tell (){
	return this.say();
	//等同于 return super.say();
	}
}
let child1 = new Child();
Child.tell(); // 这是静态方法
Child.say(); // 这是静态方法

二、静态属性

暂时没有关键字来定义,想要实现的话就在定义完类之后直接在类上添加属性,然后获取的时候通过类名来获取这个属性。

class Person{
	constructor(name="xf",age){
		this.name = name;
		this.age = age;
	}
	static say(){
		console.log("这是静态方法");
	}
}
// 模拟静态属性
Person.type = "这是模拟的静态属性";
//访问静态属性
console.log(Person.type); // 这是模拟的静态属性

猜你喜欢

转载自blog.csdn.net/m0_38134431/article/details/84317437