new 操作符做了哪些事
let Person = function (name, age) {
this.name = name
this.age = age
return 'tom'
}
Person.prototype.showInfo = function () {
console.log(this.name + ': ' + this.age);
}
let p = new Person('tom', 5)
console.log(p);
经验证当构造函数的返回结果为对象(不为空)或者 函数时,返回该结果,否则返回创建的对象。
-
创建了一个空的简单JS对象(即{})
-
为新创建的对象添加属性__proto__,将该属性链接至构造函数的原型对象
-
将构造函数的this指向这个对象
-
执行构造函数,并返回结果。 如果构造函数返回对象,则返回该对象;否则,返回刚创建的新对象(空对象)。
手写 new
根据上面得到的new操作符需要做的事,我们来手写new
function myNew(fn,...args){
if(typeof fn !== 'function'){
throw 'fn must be function'
}
let obj = {}
obj.__proto__ = fn.prototype
let result = fn.apply(obj,args)
if(typeof result === 'object' && result !== null || typeof result === 'function'){
return result
} else {
return obj
}
}
let Person = function (name, age) {
this.name = name
this.age = age
// return [1, 2]
}
Person.prototype.showInfo = function () {
console.log(this.name + ': ' + this.age);
}
let p1 = myNew(Person, 'jerry', 7)
console.log(p1);
p1.showInfo(); //jerry: 7
let p = new Person('tom', 5)
console.log(p);
p.showInfo();