一、new

用于创建用户定义的对象实例 或 创建具有构造函数的内置对象实例。

// 语法
new constructor[([arguments])]

1、使用规则

当执行 new Foo(...) 时,会发生以下事情:

  • 创建一个继承自 Foo.prototype 的新对象;
  • 使用指定参数调用构造函数,并将 this 绑定到新对象(new Foo 等同于 new Foo(),表示没有指定参数)。
  • 构造函数返回值就是 new 表达式结果。如果构造函数没有显式返回,则使用步骤1创建的对象(通常构造函数没有return 语句)。
// 实例
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const car1 = new Car('Eagle', 'Talon TSi', 1993);
console.log(car1.make);    // "Eagle"

2、new.target

可以检测一个函数是否通过 new 被调用。

// 1、检查函数
function Foo() {
  if (!new.target) 
    throw "Foo() 只能用 new 来调用";
  
  console.log("调用成功");
}
Foo();         // Uncaught Foo() 只能用 new 来调用
new Foo();     // 调用成功

// 2、查看类中构造函数
class A {
    constructor() {
        console.log(new.target.name);
    }
}
class B extends A { constructor() { super(); } }
var a = new A(); // A
var b = new B(); // B

二、参考文档

Learn_anything
7 声望0 粉丝

收集互联网优质资源!