//?先一本正經(jīng)的創(chuàng)建一個(gè)構(gòu)造函數(shù),其實(shí)該函數(shù)與普通函數(shù)并無區(qū)別
var?Person?=?function(name,?age)?{
????this.name?=?name;
????this.age?=?age;
????this.getName?=?function()?{
????????return?this.name;
????}
}
??//?將構(gòu)造函數(shù)以參數(shù)形式傳入
??function?New(func)?{
??????//?聲明一個(gè)中間對(duì)象,該對(duì)象為最終返回的實(shí)例
??????var?res?=?{};
??????if?(func.prototype?!==?null)?{
??????????//?將實(shí)例的原型指向構(gòu)造函數(shù)的原型
??????????res.__proto__?=?func.prototype;
??????}
??????//?ret為構(gòu)造函數(shù)執(zhí)行的結(jié)果,這里通過apply,將構(gòu)造函數(shù)內(nèi)部的this指向修改為指向res,即為實(shí)例對(duì)象
??????var?ret?=?func.apply(res,?Array.prototype.slice.call(arguments,?1));
??????//?當(dāng)我們?cè)跇?gòu)造函數(shù)中明確指定了返回對(duì)象時(shí),那么new的執(zhí)行結(jié)果就是該返回對(duì)象
??????if?((typeof?ret?===?"object"?||?typeof?ret?===?"function")?&&?ret?!==?null)?{
??????????return?ret;
??????}
??????//?如果沒有明確指定返回對(duì)象,則默認(rèn)返回res,這個(gè)res就是實(shí)例對(duì)象
??????return?res;
??}
??//?通過new聲明創(chuàng)建實(shí)例,這里的p1,實(shí)際接收的正是new中返回的res
??var?p1?=?New(Person,?'tom',?20);
??console.log(p1.getName());
??//?當(dāng)然,這里也可以判斷出實(shí)例的類型了
??console.log(p1?instanceof?Person);?//?true這種思路對(duì)嗎?
JavaScript中構(gòu)造函數(shù)new操作符的理解
夏目祐太
2017-04-03 18:38:42