Skip to content

new

new 是 关键字

new 的意义是重复创建 相同的数据结构

构造函数的两个约定:

  1. 它们的命名以大写字母开头。
  2. 它们只能由 "new" 操作符来执行。

具体实现

js
function User(name) {
  // this = {};(隐式创建)

  // 添加属性到 this
  this.name = name;
  this.isAdmin = false;

  // return this;(隐式返回)
}

函数被使用 new 时:

  1. 一个新的空对象被创建并分配给 this。
  2. 函数体执行。通常它会修改 this,为其添加新的属性。
  3. 返回 this 的值。

在构造函数中,返回基本类型,会被忽略,只有返回对象才会生效

从技术上讲,任何函数(除了箭头函数)都可以当作构造函数。但是不要这样做!如:

const user = new function () {
  this.name = ""
};

new.target

new.target 属性来检查它是否被使用 new 进行调用了。

new.target 是个函数,等于自己本身.

js
new User(); // [Function: User]