Skip to content

[实践系列]模拟实现new操作符 #6

Open
@webfansplz

Description

@webfansplz

new操作符做了什么?

image

  • 创建一个新对象
  • 新对象继承了构造函数的原型
  • 构造函数的this指向新对象,并执行构造函数。
  • 最后隐式的返回this,即新对象。

如果我们在构造函数中进行显式返回,会发生什么?

image

image

由此我们可以得出结论:构造函数如果返回基本类型,则会忽略,还是返回原来的this(新对象).如果返回的是引用类型,则会对该返回值进行处理,返回该返回值。

new操作符的模拟实现

知道new操作符做了什么,我们要实现就不难了,直接上代码!

image

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions