JS 类以及 extends 关键字

本文介绍了JavaScript中的类和继承概念,包括类的定义、构造函数、方法的添加,以及如何使用`extends`关键字进行类的继承。通过示例展示了如何创建Car类及其对象,以及如何派生出Square类并覆盖父类方法。还提到了可以派生内置错误对象,如自定义HttpError类。最后,展示了如何在实际应用中使用这些自定义类来处理错误情况。
摘要由CSDN通过智能技术生成

类是 ES6 的语法, 是对象的模板。函数可以先调用再定义,但类要先定义再使用。

语法:

class ClassName {
  /* 如果没有此函数,JS会自动提供一个空的constructor() */
  constructor() { ... }
  
  // 为类添加方法: optional
  method_1() { ... }
  method_2() { ... }
  method_3() { ... }
}

下面的例子先创建一个类 Car, 然后创建两个类 Car 的对象:

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
}

let myCar1 = new Car("Ford", 2014);
let myCar2 = new Car("Audi", 2019);

使用 extends 关键字派生新的类,在派生类中,在使用 this 关键字之前,必须先调用super ()

class Square extends Polygon {
  constructor(length) {
    // Here, it calls the parent class' constructor with lengths
    // provided for the Polygon's width and height
    super(length, length);
    // Note: In derived classes, super() must be called before you
    // can use 'this'. Leaving this out will cause a reference error.
    this.name = 'Square';
  }

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

也可以派生JS的内建对象,例如 Error

class HttpError extends Error {
  constructor(message, errorCode) {
    super(message);
    this.code = errorCode;
  }
}

然后使用这个自定义的类:

const getPlaceById = async (req, res, next) => {
  const placeId = req.params.pid;
  let place;
  try {
    place = await Place.findById(placeId);
  } catch (err) {
    const error = new HttpError(
      "Something went wrong, could not find a place",
      500
    );
    return next(error);
  }

  if (!place) {
    const error = new HttpError(
      "Could not find place for the provided id.",
      404
    );
    return next(error);
  }
  res.json({ place: place.toObject({ getters: true }) });
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值