JavaScript 类(class)

在JavaScript中,类(class)是一种用于创建对象的构造函数的语法糖。它是JavaScript的面向对象编程(OOP)的基础,通过定义类来创建具有相似特征和行为的对象。

下面是一个简单的示例,展示了如何使用类来创建对象:

```javascript
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
}

// 创建 Person 类的实例
const person1 = new Person("Alice", 25);
const person2 = new Person("Bob", 30);

person1.sayHello(); // 输出:Hello, my name is Alice and I'm 25 years old.
person2.sayHello(); // 输出:Hello, my name is Bob and I'm 30 years old.
```

在上面的例子中,我们定义了一个名为`Person`的类,它有两个属性`name`和`age`,以及一个方法`sayHello`。构造函数`constructor`用于初始化类的属性。通过使用`new`关键字和类名,我们可以创建`Person`类的实例。然后,我们可以通过调用实例的方法来操作对象。

类还支持继承,允许你创建一个新的类,并继承来自父类的属性和方法。下面是一个简单的继承示例:

```javascript
class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name}, I'm ${this.age} years old, and I'm in grade ${this.grade}.`);
  }
}

const student = new Student("Carol", 18, 12);
student.sayHello(); // 输出:Hello, my name is Carol, I'm 18 years old, and I'm in grade 12.
```

在这个例子中,我们定义了一个名为`Student`的子类,它继承了`Person`类的属性和方法。通过使用`super`关键字,我们可以在子类的构造函数中调用父类的构造函数,以初始化继承的属性。子类还可以重写父类的方法,从而改变其行为。

需要注意的是,JavaScript的类语法只是一种语法糖,底层仍然是基于原型的继承。在运行时,类被转换为使用原型和构造函数来创建对象的方式。

当然!以下是一个更具体的示例,展示了如何使用JavaScript类创建一个简单的图形对象层次结构:

```javascript
class Shape {
  constructor(color) {
    this.color = color;
  }

  getColor() {
    return this.color;
  }

  area() {
    console.log("This method should be overridden by subclasses.");
  }
}

class Circle extends Shape {
  constructor(color, radius) {
    super(color);
    this.radius = radius;
  }

  area() {
    return Math.PI * this.radius * this.radius;
  }
}

class Rectangle extends Shape {
  constructor(color, width, height) {
    super(color);
    this.width = width;
    this.height = height;
  }

  area() {
    return this.width * this.height;
  }
}

// 创建 Circle 和 Rectangle 实例
const circle = new Circle("red", 5);
const rectangle = new Rectangle("blue", 4, 6);

console.log(circle.getColor());      // 输出:red
console.log(circle.area());          // 输出:78.53981633974483

console.log(rectangle.getColor());   // 输出:blue
console.log(rectangle.area());       // 输出:24
```

在上面的示例中,我们定义了一个基类`Shape`,它有一个构造函数接受颜色参数,并提供了获取颜色和计算面积的方法。然后,我们创建了两个子类`Circle`和`Rectangle`,它们分别继承了`Shape`类。

子类`Circle`有一个额外的属性`radius`,并重写了父类的`area`方法来计算圆的面积。子类`Rectangle`有两个额外的属性`width`和`height`,并同样重写了父类的`area`方法来计算矩形的面积。

我们可以通过创建相应的子类实例,并使用继承自父类的方法来操作对象。每个对象都有自己的属性和方法,以及从父类继承的通用属性和方法。

这个例子展示了如何使用类和继承创建一个简单的图形对象层次结构,但你可以根据自己的需求扩展和定制类和子类,以适应更复杂的场景。

猜你喜欢

转载自blog.csdn.net/smarten57/article/details/131134305
今日推荐