我正在阅读 this example在 Promise
上。我意识到 Error
构造函数不是用 new
运算符调用的。那为什么它有效呢?
最佳答案
因为 the specification says构造函数应该检查它是如何被调用的,如果它不是用 new
调用的,它应该用 new
调用它自己并返回它。
The Error constructor is the %Error% intrinsic object and the initial value of the Error property of the global object. When Error is called as a function rather than as a constructor, it creates and initializes a new Error object. Thus the function call Error(…) is equivalent to the object creation expression new Error(…) with the same arguments.
在 JS 中的示例实现可能如下所示:
function MyC(foo, bar) {
if (!(this instanceof MyC)) {
return new MyC(foo, bar);
}
this.foo = foo;
this.bar = bar;
}
关于javascript - 没有新运算符的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35888140/