1.创建空对象
let obj = new Object()
2.设置原型链,将构造函数的作用域赋值给新对象(绑定this)
Object.setPrototypeOf(obj,Con.prototype)
下面方式更容易理解
obj.__proto__ = Con.prototype
3.调用构造函数
let result = Con.apply(obj,args)
4.返回新对象
return typeof result ==='object'?result:obj
完整测试和使用方法如下:
function create(Con, ...args){
let obj = new Object()
Object.setPrototypeOf(obj, Con.prototype);
let result = Con.apply(obj, args);
return typeof result ==='object'?result:obj
}
// 测试
function company(name, address) {
this.name = name;
this.address = address;
}
var com = create(company, 'zs', 'beijing');
console.log(com);