Front-end-learning-to-organize-notes icon indicating copy to clipboard operation
Front-end-learning-to-organize-notes copied to clipboard

new操作符之后的操作

Open Chocolate1999 opened this issue 4 years ago • 1 comments

Chocolate1999 avatar Jan 21 '21 09:01 Chocolate1999

new 运算符操作过程

当一个函数被使用 new 运算符执行时,它按照以下步骤:

一个新的空对象被创建并分配给 this。 函数体执行。通常它会修改 this,为其添加新的属性。 返回 this 的值。 以下面 User 方法为例:

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

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

  // return this;(隐式返回)
}
const user= new User('Chocolate');
console.log(user.name, user.isAdmin); // "Chocolate" false

当我们执行 new User('Chocolate') 时,发生以下事情:

  • 一个继承自 User.prototype 的新对象被创建;
  • 使用指定参数调用构造函数 User ,并将 this 绑定到新创建的对象;
  • 由构造函数返回的对象就是 new 表达式的结果。如果构造函数没有显式返回一个对象,则使用步骤1创建的对象。

「需要注意」:

  • 一般情况下,构造函数不返回值,但是开发者可以选择主动返回对象,来覆盖正常的对象创建步骤;
  • new User 等同于 new User() ,只是没有指定参数列表,即 User 不带参数的情况;
let user = new User; // <-- 没有参数
// 等同于
let user = new User();
  • 任何函数都可以作为构造器,即都可以使用 new 运算符运行。

本文参考:

【JS】676- 1.1w字 | 初中级前端 JavaScript 自测清单 - 2

Chocolate1999 avatar Jan 23 '21 02:01 Chocolate1999