new 關鍵字實現(xiàn)了如下過程
1.創(chuàng)建一個空對象 obj ={}
2.鏈接到原型 obj.proto = Constructor.prototype
3.綁定this值 Constructor.call(obj)
4.返回新對象
function create(){
//創(chuàng)建一個空對象
let obj = new Object();
//獲取構造函數(shù)
let Constructor = [].shift.call(arguments);
//鏈接到原型
obj.__proto__ = Constructor.prototype;
//綁定this值
let result = Constructor.apply(obj, arguments);//使用apply,將構造函數(shù)中的this指向新對象,這樣新對象就可以訪問構造函數(shù)中的屬性和方法
//返回新對象
return typeof result === "object" ? result : obj;//如果返回值是一個對象就返回該對象溶推,否則返回構造函數(shù)的一個實例對象
}