Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写 new 关键字 #1

Open
toFrankie opened this issue Oct 28, 2021 · 0 comments
Open

手写 new 关键字 #1

toFrankie opened this issue Oct 28, 2021 · 0 comments
Labels
2021 2021 年撰写 手写系列 与手写实现相关的文章

Comments

@toFrankie
Copy link
Owner

toFrankie commented Oct 28, 2021

原理

先了解下 new 关键字都做了些什么工作:

  1. 隐式创建一个实例对象 this(空对象);
  2. 将实例对象原型(__proto__)指向构造函数的原型对象(prototype);
  3. 开始执行构造函数,一般会伴随着实例对象属性、方法的绑定;
  4. 返回结果。需要注意的是,上一步执行构造函数返回的结果,若为引用值,则直接返回该值,否则返回实例对象。

思路

知道原理之后,手写就有思路了,我们将会使用以下方式进行调用:

myNew(ctor, arg1, arg2, ...)
  • ctor 接受一个构造函数。

  • arg1, arg2, ...(可选)指定参数列表。

实现

代码实现,如下:

function myNew() {
  // 获取构造函数、参数列表
  const [Ctor, ...args] = arguments

  // 创建实例对象,并指定原型
  const _this = {}
  _this.__proto__ = Ctor.prototype // 或使用标准方法 Object.setPrototypeOf(_this, Ctor.prototype)

  // 执行构造函数,并注意 this 指向
  const res = Ctor.apply(_this, args)

  // 返回结果
  return res instanceof Object ? res : _this
}

优化

既然我们直接使用了 ES6 的语法,我们不妨将创建实例对象的步骤改用 Object.create() 来处理,再简化一下:

function myNew(Ctor, ...args) {
  const _this = Object.create(Ctor.prototype)
  const res = Ctor.apply(_this, args)
  return res instanceof Object ? res : _this
}

Usage

function Foo(name, age) {
  this.name = name
  this.age = age
}

const foo = myNew(Foo, 'Frankie', 20) // Foo { name: 'Frankie', age: 20 }
@toFrankie toFrankie added the 手写系列 与手写实现相关的文章 label Mar 26, 2022
@toFrankie toFrankie added the 2021 2021 年撰写 label Apr 26, 2023
@toFrankie toFrankie changed the title 手写系列之 new 关键字的实现 手写 new 关键字 Apr 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
2021 2021 年撰写 手写系列 与手写实现相关的文章
Projects
None yet
Development

No branches or pull requests

1 participant