javascript - 没有新运算符的错误

标签 javascript constructor

我正在阅读 this examplePromise 上。我意识到 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/

相关文章:

C++ 在构造函数中通过引用传递对象和复制构造函数混淆

java - 在另一个字符串中找到该字符串的字符有多少次

scala - 如何向父类(super class)构造函数提供转换后的参数,同时避免使用 Scala 进行内联计算

JavaScript 中的 PHP 代码获取变量

javascript - MapReduce 上的 Riak 排序

javascript - 多设备混合应用程序的 Web 服务错误

java - 在Java中如何使用构造函数来初始化不同类的对象?

c# - 在初始化惰性实例时将参数传递给构造函数

php - 如何使用 View 按钮在 Controller 中调整 foreach 的速度?

javascript - 如何为特定的音频播放器编写JavaScript代码