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
chenfan0 opened this issue May 27, 2022 · 0 comments
Open

手写题:如何实现new操作? #6

chenfan0 opened this issue May 27, 2022 · 0 comments

Comments

@chenfan0
Copy link
Member

new操作时做了什么?

  • 创建一个空对象
  • 将创建的空对象的__proto__属性指向被new函数的prototype属性
  • 将函数的this指向创建出来的空对象,并且执行函数
  • 判断函数本身的返回值是否为函数或者对象类型,如果函数本身返回的就是一个对象类型,那么直接返回函数本身返回的对象。如果函数本身返回的是一个基本数据类型,那么就返回一开始创建出来的对象

代码实现

function myNew(fn, ...args) {
  // 判断传递的参数是否合法
  if (typeof fn !== 'function') {
    throw new Error('传递的参数不能被new');
  }
  // 创建一个空对象,并且将该对象的__proto__属性指向fn.prototype
  const obj = Object.create(fn.prototype)
  // 执行函数体,并将this指向创建出来的对象
  const fnResult = fn.apply(obj, args)
  // 判断函数本身返回值是否为函数或者对象类型
  if (typeof fnResult === 'object' || typeof fnResult === 'function') {
    return fnResult
  }

  return obj
}
@chenfan0 chenfan0 added handwritten-code today 每日一题。 and removed today 每日一题。 labels May 27, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

1 participant