类是 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 }) });
};