loading...

re: How can JavaScript Error be both a function and a class? VIEW POST

FULL DISCUSSION
 

Yes you can replicate it yourself, just check if this is an instance of the constructor and if it isn't, call the function with new internally

function doSomething(message) {
    if (this instanceof doSomething) {
        this.message = message
    } else {
        return new doSomething(message)
    }
}
console.log(doSomething("1"))
console.log(new doSomething("2"))

Not sure it's particularly wise to do it though, just seems like it will cause confusion and inconsistency down the road.

 

Yup, I definitely agree with refraining from its usage. The Error "class" is pretty much just an exception to the rule, not a robust language feature.

 
code of conduct - report abuse