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对象过程以及手写实现new操作 #24

Open
heyushuo opened this issue Dec 27, 2019 · 0 comments
Open

new对象过程以及手写实现new操作 #24

heyushuo opened this issue Dec 27, 2019 · 0 comments

Comments

@heyushuo
Copy link
Owner

一、new 来调用函数,或者说发生构造函数调用时,会自动执行哪些操作呢?

  • 创建(或者说构造)一个全新的对象
  • 这个新对象会被执行 [[ 原型 ]] 连接(即实例的__proto__ 指向 构造函数的原型对象prototype)。
  • 这个新对象会绑定到函数调用的 this(this 绑定)。
  • 如果函数没有返回其他对象,那么 new 表达式中的函数调用会自动返回这个新对象

二、手写实现 new 操作

//第一个参数传构造函数
function creat() {
  //1.创建一个全新对象
  var obj = {};
  //获取到第一个参数(即为构造函数)
  var Con = [].shift().call(arguments);
  //2.这个新对象会被执行 [[ 原型 ]] 连接
  obj.__proto__ = Con.prototype;
  //3.this 绑定
  Con.apply(obj, arguments);
  //返回这个新对象
  return obj;
}
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