描述過程
1.創(chuàng)建一個js對象
2.這個對象的_proto_要指向構(gòu)造函數(shù)的原型prototype
3.將這個對象作為this的上下文
4.如果這個函數(shù)沒有返回對象枉疼,則返回this
代碼實現(xiàn)
function myNew(fn, ...args) {
let instance = Object.create(fn.prototype);// 1轨帜、2步
let res = fn.apply(instance, args); // 改變this指向
return typeof res === 'object' ? res: instance; // 確保返回的是一個對象
}
關(guān)于返回值
在new的時候魄咕,會對構(gòu)造函數(shù)的返回值做判斷:
1、如果返回值是基礎(chǔ)數(shù)據(jù)類型蚌父,則忽略返回值哮兰;
2、如果返回值是引用數(shù)據(jù)類型梢什,則使用return 這個返回值奠蹬。