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

JavaScript: new 后发生了什么 #34

Open
xvno opened this issue Apr 14, 2019 · 1 comment
Open

JavaScript: new 后发生了什么 #34

xvno opened this issue Apr 14, 2019 · 1 comment

Comments

@xvno
Copy link
Owner

xvno commented Apr 14, 2019

No description provided.

@xvno
Copy link
Owner Author

xvno commented Apr 16, 2019

在这里考虑如下几条

  • Fn 作为某个类的构造函数
  • neu() 作为关键字new的别名函数
    则有
let fn = neu(Fn); // fn = new Fn();

neu的实现:

function neu (Fn) {
  if(typeof Fn !== 'function') {
    throw new TypeError('Not a constructor');
  }
  let obj = {};
  let result = Fn.call(obj);

  let type = typeof result;
  if(type === 'object' || type === 'function') {
    obj = result
  }
  Object.setPrototypeOf(obj, Fn.prototype);
  return obj;
}

@xvno xvno changed the title 前端: JavaScript: new 后发上了什么 前端: JavaScript: new 后发生了什么 Dec 20, 2019
@xvno xvno changed the title 前端: JavaScript: new 后发生了什么 JavaScript: new 后发生了什么 Feb 9, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant