- 拿到构造函数
- 创建一个空对象o
- 执行构造函数,并把this指向这个空对象,获取返回值res
- 返回值res如果是Object的实例,直接返回
- 返回值res如果不是Object的实例,返回o,并将
o.__proto__指向构造函数的prototype。
const mockNew = function (){
const args = Array.prototype.slice.call(arguments)
const [_class, ...restArg] = args
const resObj = {}
const res = _class.apply(resObj, restArg)
if (res instanceof Object) {
return res
} else {
resObj.__proto__ = _class.prototype
return resObj
}
}
function Demo (b) {
this.a = b
}
function Demo2 () {
return Demo2 // 有没有return一个对象,是new的分水岭
}
const demo = mockNew(Demo)
console.log(demo instanceof Demo); // true
const demo2 = mockNew(Demo2)
console.log(demo2 instanceof Demo2); // false
面试题
function f() {
return f; // 函数 f 继承自对象,所以 new 之后会返回函数本身
}
console.log(new f() instanceof f);
// 函数的上层原型链(__proto__)是 native code,native code 上层的原型链是 Object,不和 f.prototype (一个对象)相等,所以返回值为 false