(1)创建一个新对象
(2)将构造函数的作用域赋给新对象(因此this就指向了这个新对象)
(3)执行构造函数中的代码(为这个新对象添加属性)
(4)返回新对象
js实现new
function person(name) {
this.name = name;
}
function _new() {
//1创建一个新对象
let target = {};
let [constructor, ...args] = [...arguments]
//2原型链链接
target.__proto__ = constructor.prototype;
//3将构造函数的属性和方法添加到这个新对象中
let result = constructor.apply(target, args)
if(result && (typeof result == "object" || typeof result == "function")) {
return result
}
return target
}