类(classes)
- ES6 引入了类的语法,使得面向对象编程更加直观和易于理解。虽然底层依然是基于原型的继承机制,但语法更接近传统的面向对象语言。
首先,定义类,之后创建实例调用, 其中constructor是构造器,用来创建类的实例。 注意:定义类时,名称首字母要大写,因为创建实例时由new创建的。
// 定义类
class Person {
//constructor 是类的构造函数,用来创建类的实例
constructor(name, age){
this.name = name;
this.age = age;
}
sayHello(){
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// 创建实例
const person1 = new Person("John", 25);
person1.sayHello(); // 输出: Hello, my name is John and I am 25 years old.
子类继承父类的属性和方法: 如:
class Star extends Person {
constructor(name, age, fans){
super(name, age);
this.fans = fans;
}
}
// 创建子类的实例
const star1 = new Star("Mary", 20, 10000);
star1.sayHello(); // 输出: Hello, my name is Mary and I am 20 years old.
console.log(star1.fans); // 输出: 10000
extends 父类名 用于继承父类 子类的super继承父类中构造的函数和方法