JavaScript/NodeJS: 检查父方法的 instanceof
JavaScript/NodeJS: checking instanceof for parent method
在 Solid 的 NodeJS 实现中,我可以看到以下内容:
module.exports = HTTPError
function HTTPError (status, message) {
if (!(this instanceof HTTPError)) {
return new HTTPError(status, message)
}
这背后的意义是什么?在哪种情况下,所述方法实例不会通过 instanceof
检查?我认为这不是多余的,正如我现在所想的那样,但找不到其背后的逻辑。
差异的发生取决于 new
关键字的存在。
考虑以下示例:
function HTTPError(status, message) {
if (!(this instanceof HTTPError)) {
console.log("called without new. Status is " + status);
return new HTTPError(status, message)
} else {
console.log("called with new. Status is " + status);
}
this.status = status;
}
const i = HTTPError(500);
const i2 = new HTTPError(400);
console.log(i);
console.log(i2);
this instanceof HTTPError
检查的目的是允许 class 作为常规函数调用。 HTTPError
class 模仿内置的 JavaScript class 类似 Error
的东西可以用和不用 new
构造:
Error() instanceof Error; // true
HTTPError() instanceof HTTPError; // true
这允许两个调用成为可能,作为一个 class 实例:
let myError = new HTTPError('status', 'message');
并作为函数调用:
let myError = HTTPError('status', 'message');
在函数调用的情况下,this
在函数体中未定义,因此,返回 new HTTPError
将创建 class.
的实例
在 Solid 的 NodeJS 实现中,我可以看到以下内容:
module.exports = HTTPError
function HTTPError (status, message) {
if (!(this instanceof HTTPError)) {
return new HTTPError(status, message)
}
这背后的意义是什么?在哪种情况下,所述方法实例不会通过 instanceof
检查?我认为这不是多余的,正如我现在所想的那样,但找不到其背后的逻辑。
差异的发生取决于 new
关键字的存在。
考虑以下示例:
function HTTPError(status, message) {
if (!(this instanceof HTTPError)) {
console.log("called without new. Status is " + status);
return new HTTPError(status, message)
} else {
console.log("called with new. Status is " + status);
}
this.status = status;
}
const i = HTTPError(500);
const i2 = new HTTPError(400);
console.log(i);
console.log(i2);
this instanceof HTTPError
检查的目的是允许 class 作为常规函数调用。 HTTPError
class 模仿内置的 JavaScript class 类似 Error
的东西可以用和不用 new
构造:
Error() instanceof Error; // true
HTTPError() instanceof HTTPError; // true
这允许两个调用成为可能,作为一个 class 实例:
let myError = new HTTPError('status', 'message');
并作为函数调用:
let myError = HTTPError('status', 'message');
在函数调用的情况下,this
在函数体中未定义,因此,返回 new HTTPError
将创建 class.