【问题标题】:What is difference between these Three and which is best? and Why message property is hidden?这三个有什么区别,哪个最好?为什么隐藏消息属性?
【发布时间】:2022-01-16 04:00:29
【问题描述】:
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)时显示值

【问题讨论】:

  • 查一下自己的属性和继承的属性的区别。

标签: javascript node.js class object


【解决方案1】:
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)

【讨论】:

    【解决方案2】:
    • AppError 类扩展(继承)Error
    • 这意味着 AppError 的 this 上下文包括 Error 类中定义的属性和方法,以及 AppError 为自己定义的任何属性和方法。
    • 在子类构造函数中调用super(arguments)调用父类构造函数

    让他们知道,没有什么问题太小或太奇怪了:)

    Js 很有趣,试试这本书

    https://javascript.info/

    https://eloquentjavascript.net/ :)

    【讨论】:

      猜你喜欢
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 2015-02-14
      • 1970-01-01
      • 2017-03-27
      • 2012-12-04
      • 2011-10-06
      相关资源
      最近更新 更多