JS中new操作符做了什么?
1.new操作符做了什么
new 運(yùn)算符創(chuàng)建一個用戶定義的對象類型的實(shí)例或具有構(gòu)造函數(shù)的內(nèi)置對象的實(shí)例。new 關(guān)鍵字會進(jìn)行如下的操作:
創(chuàng)建一個空的簡單JavaScript對象(即{});
鏈接該對象(即設(shè)置該對象的構(gòu)造函數(shù))到另一個對象 ;
將步驟1新創(chuàng)建的對象作為this的上下文 ;
如果該函數(shù)沒有返回對象,則返回this。
2.簡單實(shí)現(xiàn)
function create(Con, ...args){
// 創(chuàng)建一個空的對象
let obj = Object.create(null);
// 將空對象指向構(gòu)造函數(shù)的原型鏈
Object.setPrototypeOf(obj, Con.prototype);
// obj綁定到構(gòu)造函數(shù)上,便可以訪問構(gòu)造函數(shù)中的屬性,即obj.Con(args)
let result = Con.apply(obj, args);
// 如果返回的result是一個對象則返回
// new方法失效,否則返回obj
return result instanceof Object ? result : obj;
}
// 測試
function company(name, address) {
this.name = name;
this.address = address;
}
var company1 = create(company, 'yideng', 'beijing');
console.log('company1: ', company1);
作者:Vam的金豆之路
主要領(lǐng)域:前端開發(fā)
我的微信:maomin9761
微信公眾號:前端歷劫之路