new 关键字做了哪些操作?
- 创建一个空的简单 JavaScript 对象(即
{}
); - 为步骤 1 新创建的对象添加属性
__proto__
,将该属性链接至构造函数的原型对象; - 将步骤 1 新创建的对象作为
this
的上下文; - 如果该函数没有返回对象,则返回
this
。
function newFunc(consFn, ...argms) {
let newObj = {
__proto__: consFn.prototype
}
let backObj = consFn.apply(newObj, argms)
if (backObj && typeof backObj === 'object') {
return backObj
}
return newObj
}
function Fn(name) {
this.age = 20
this.name = name
}
const testFn = new newFunc(Fn, 'lisi')
const testFn2 = new Fn('lisi ')
console.log(testFn)
console.log(testFn2)