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操作符 #6

Open
webfansplz opened this issue Mar 5, 2019 · 1 comment
Open

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

webfansplz opened this issue Mar 5, 2019 · 1 comment

Comments

@webfansplz
Copy link
Owner

new操作符做了什么?

image

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

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

image

image

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

new操作符的模拟实现

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

image

@zhw2590582
Copy link

假如res刚好等于null,理应也返回o的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants