模拟new的实现
使用new操作符发生了什么
-
在构造函数中创建一个空对象
-
把构造函数的this指向这个新的空对象
-
把构造函数的prototype属性指向的原型对象赋值给这个空对象的__proto__属性
-
返回这个空对象
代码模拟
function Person(name,age){
this.name = name
this.age = age
}
function newSimulate(){
let obj = {}
//这里[]是为了调用shift方法,该方法会返回数组的首项,即传入的参数首位
let fn = [].shift.apply(arguments)
//把空对象的__proto__指向构造函数的原型对象
obj.__proto__ = fn.prototype
//...spread操作符展开数组,用变量result保存返回的结果
let result = fn.call(obj,...arguments)
return typeof result === 'object'? result:obj
}
var p1 = newSimulate(Person,'xuan',18)
p1 instanceof Person //true
p1.constructor === Person //true