# new 关键字原理及实现 new
# new 操作符做了什么?
- new 一个构造函数后,函数内部创建一个空对象,由 this 来引用,并且继承了该函数的原型;
 - 函数执行,给 this 添加属性和方法
 - 最后隐式返回 this
 
# 实现 new
ES5 写法
function _new(fn, ...args) {
  let obj = {}; //创建空对象
  obj.__proto__ = fn.prototype; //继承函数的原型
  //Object.setPrototypeOf(obj,fn.prototype)
  const result = fn.call(obj, ...args); //给 this 添加属性和方法
  return result && result instanceof Object ? result : obj; //最后隐式返回 this
}
 1
2
3
4
5
6
7
2
3
4
5
6
7
ES6 写法
function _new(fn, ...args) {
  let obj = Object.create(fn.prototype); //创建空对象,继承函数的原型
  let result = fn.call(obj, ...args); //给this添加属性和方法
  return result && result instanceof Object ? result : obj; //最后隐式返回 this
}
 1
2
3
4
5
2
3
4
5