class AppError extends Error{
constructor(message,statusCode){
super(message)
this.statusCode = statusCode
}
}
AND
class AppError extends Error{
constructor(message,statusCode){
super(message)
this.message=message
this.statusCode = statusCode
}
}
AND
class AppError{
constructor(message,statusCode){
this.message = message
this.statusCode = statusCode
}
}
我正在使用 mongo 處理 nodeJs 專案。在錯誤處理期間,我創建了這個類,但沒有理解這些之間的差異。AND 哪個是最好的方法?我是否擴展到錯誤類并直接分配訊息屬性是否重要?最重要的是。當我列印使用第一類創建的物件時,為什么缺少訊息屬性?雖然當我顯式列印它時(例如 err.message)顯示值
uj5u.com熱心網友回復:
class Error {
constructor(message) {
this.message = message
}
}
class AppError extends Error{
constructor(message,statusCode){
super(message) // This calls the constructor of the parent
this.statusCode = statusCode
}
}
// AND
class AppError extends Error{
constructor(message,statusCode){
super(message) // This calls the parent constructor
this.message=message // This ovverrides the previous line
this.statusCode = statusCode
}
}
// AND
class AppError{
constructor(message,statusCode){
this.message = message // This is just without the extended class
this.statusCode = statusCode
}
}
另一個例子:這表明父建構式被呼叫,但你缺少雞肉和食物
class Error {
constructor(message, chicken, food) {
this.message = message
this.chicken = chicken
this.food = food
}
}
class AppError extends Error {
constructor(message, statusCode) {
super(message)
this.statusCode = statusCode
}
}
let x = new AppError("Message", "Errorcode")
console.log(x)
為了減少冗余代碼并且您有很多類引數,它可能如下所示:
class Animal {
constructor(price, size, age) {
this.price = price
this.size = size
this.age = age
}
}
class Cat extends Animal {
constructor(cattype, price, size, age) {
super(price, size, age) // This is way shorter than repeating what is written in the Animal class
this.cattype = cattype
}
}
let x = new Cat("weirdtype", "500Euros", "BigSize", "OldAge")
console.log(x)
uj5u.com熱心網友回復:
- 類
AppError延伸(繼承)從Error類 - 這意味著 AppError 的
this背景關系包括在 Error 類中定義的屬性和方法,以及AppError為自身定義的任何屬性和方法。 - 呼叫
super(arguments)在子類的建構式呼叫父類的構造
讓他們知道沒有什么問題太小或太奇怪而無法提出:)
Js很有趣試試這本書
https://javascript.info/
https://eloquentjavascript.net/ :)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/379550.html
標籤:javascript 节点.js 班级 目的
下一篇:動態實體化鏈接的物件鏈
