構(gòu)造函數(shù)模式 構(gòu)造函數(shù)其實(shí)和工廠方式差不多。從代碼量上來(lái)說(shuō),就是省略了構(gòu)造函數(shù)內(nèi)部沒(méi)有創(chuàng)建一個(gè)對(duì)象。 代碼如下: function Car(sColor) { this.color = sColor; this.showColor = function () { alert(this.color); } } oCar = new Car("red"); oCar.showColor();
其實(shí)此隱含的對(duì)象已經(jīng)在 new 以后就被實(shí)例化了。默認(rèn)情況下,構(gòu)造函數(shù)返回的就是其 this 的值(所以不必使用 return 返回)。但構(gòu)造函數(shù)模式和工廠模式一樣可能會(huì)重復(fù)定義方法,這點(diǎn)可以參考上述工廠模式的做法避免它(始終看起來(lái)不完美)。