new 在 JavaScript 中是實(shí)例化一個(gè)對(duì)象的操作符
實(shí)現(xiàn)一個(gè) new
- 生成了一個(gè)新的對(duì)象
- 鏈接到原型鏈
- 綁定 this
- 返回新的對(duì)象
在調(diào)用 new 的過程中會(huì)發(fā)生以上四件事情,我們也可以試著來自己實(shí)現(xiàn)一個(gè) new
function create() {
// 創(chuàng)建一個(gè)對(duì)象
const obj = new Object()
// 獲得構(gòu)造函數(shù)
let Con = [].shift.call(arguments)
// arguments 是一個(gè)偽數(shù)組,借用 Array.prototype 上的方法轉(zhuǎn)換成真正的數(shù)組
// let args = [].slice.call(arguments)
// 鏈接原型
obj.__proto = Con.prototype
// 綁定 this 寞蚌,執(zhí)行構(gòu)造函數(shù)
let result = Con.apply(obj, arguments)
// 確保 new 出來的是個(gè)對(duì)象
return typeof result === 'object' ? result : obj
}