12. new的模拟实现 - cw84973570/Learning-notes GitHub Wiki

https://github.com/mqyqingfeng/Blog/issues/13

new实现的功能:

1.创建一个新对象

2.对这个对象执行[原型](/cw84973570/Learning-notes/wiki/原型)链接(原型链接忘了)

3.将this指向这个对象

4.如果函数没有返回对象,那么返回这个对象

function objcetFactory () {
  var o = {}; // 创建新对象
  var Constructor = Array.prototype.shift.call(arguments); // 获取构造函数
  o.__proto__ = Constructor.prototype; // 执行原型链接
  var result = Constructor.apply(o, arguments); // 将this指向新对象,执行代码
  return typeof result === 'object' ? result || o : o; // 如果构造函数没有返回对象,则返回新对象
}