new关键词的作用
- 执行构造函数,返回实例对象
-
new关键词执行特点
new执行构造函数后始终返回一个对象
-
原理
首先创建了一个空对象 tempObj;
接着调用 CreateObj.call 方法,并将 tempObj 作为 call 方法的参数,这样当 CreateObj 的执行上下文创建时,它的 this 就指向了 tempObj 对象;
然后执行 CreateObj 函数,此时的 CreateObj 函数执行上下文中的 this 指向了 tempObj 对象;
最后返回 tempObj 对象。function CreateObj(){this.name = " 极客时间 "}var myObj = new CreateObj()// 内部原理var tempObj = {}CreateObj.call(tempObj)return tempObj
原理2(《JavaScript权威指南4 · P221》)
在内存中创建一个新对象
- 这个新对象内部的[[Prototype]](即proto)特性被赋值为构造函数的prototype属性
- 构造函数内部的this被赋值为这个新对象(即this指向新对象)
- 执行构造函数内部的代码(给新对象添加属性)
- 如果构造函数返回非空对象,则返回该对象;否则,返回刚创建的新对象
原理3 (拉钩·JavaScript核心原理)
function _new(ctor,...args){if(typeof ctor) throw new Error('ctor必须是一个函数')const obj = Object.create(null)obj.__proto__ = Object.create(ctor.prototype)const res = ctor.apply(obj,...args)const isObject = typeof res === 'object' && res !== nullconst isFunction = typeof res === 'function'return isObject || isFunction ? res : obj}

