JS中new操作符做了什么?
1.new操作符做了什么
new 運(yùn)算符創(chuàng)建一個(gè)用戶定義的對(duì)象類型的實(shí)例或具有構(gòu)造函數(shù)的內(nèi)置對(duì)象的實(shí)例。new 關(guān)鍵字會(huì)進(jìn)行如下的操作:
創(chuàng)建一個(gè)空的簡(jiǎn)單JavaScript對(duì)象(即{});
鏈接該對(duì)象(即設(shè)置該對(duì)象的構(gòu)造函數(shù))到另一個(gè)對(duì)象 ;
將步驟1新創(chuàng)建的對(duì)象作為this的上下文 ;
如果該函數(shù)沒(méi)有返回對(duì)象,則返回this。
2.簡(jiǎn)單實(shí)現(xiàn)
function create(Con, ...args){
// 創(chuàng)建一個(gè)空的對(duì)象
let obj = Object.create(null);
// 將空對(duì)象指向構(gòu)造函數(shù)的原型鏈
Object.setPrototypeOf(obj, Con.prototype);
// obj綁定到構(gòu)造函數(shù)上,便可以訪問(wèn)構(gòu)造函數(shù)中的屬性,即obj.Con(args)
let result = Con.apply(obj, args);
// 如果返回的result是一個(gè)對(duì)象則返回
// new方法失效,否則返回obj
return result instanceof Object ? result : obj;
}
// 測(cè)試
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
微信公眾號(hào):前端歷劫之路