前言
之前在復(fù)習(xí)的時(shí)候,經(jīng)常使用的new忽然感覺到錯(cuò)愕,不適應(yīng),今天查了資料,自己簡(jiǎn)單實(shí)現(xiàn)了一下。
new命令的作用
function Person(name){
console.log(this);
this.name=name;
}
var child=new Person;
child instanceof Person;
由上面的代碼可知道new操作符綁定了Person內(nèi)部this關(guān)鍵字,執(zhí)行了Person內(nèi)部的代碼,返回了一個(gè)對(duì)象。
new命令的原理
1.創(chuàng)建一個(gè)空對(duì)象,作為將要返回的對(duì)象實(shí)例。
2.將這個(gè)空對(duì)象的原型,指向構(gòu)造函數(shù)的prototype屬性。
3.將這個(gè)空對(duì)象賦值給函數(shù)內(nèi)部的this關(guān)鍵字。
4.開始執(zhí)行內(nèi)部的代碼。
new的簡(jiǎn)易實(shí)現(xiàn)
注意下面這種行為。
function Person(){
return {"cc":"20"}
}
var child=new Person();//{cc:"20"}
function Person(){
return null
}
var child=new Person();
根據(jù)上面的行為實(shí)現(xiàn)new操作符
function _new(constructor,params){
var args=[].slice.call(arguments);//把a(bǔ)rguments對(duì)象轉(zhuǎn)為數(shù)組
var constructor=args.shift();//取出構(gòu)造函數(shù)
var context=Object.create(constructor.prototype);//創(chuàng)建新的對(duì)象,并把對(duì)象的原型指向構(gòu)造函數(shù)的原型對(duì)象
var result=constructor.apply(context,args);//綁定this
return (typeof result==='object'&&result!=null)?result:context;//返回對(duì)象
}
var actor=_new(Person,'cc',20);
資料來(lái)源
資料來(lái)源:構(gòu)造函數(shù)與 new 命令
紅寶書(第三版)