JavaScript類的設(shè)計(jì)模式
1、構(gòu)造函數(shù)+原形(prototype)?????????
??????????
?1?//定義一個(gè)類class?
?2?function?class(sample,
){??//構(gòu)造函數(shù)?
?3????someProperty=sample;
?4????//其他屬性
?5?}?
?6?
?7?//通過指定prototype對(duì)象來實(shí)現(xiàn)類的成員定義?
?8?class.prototype={?
?9???someMethod:function(){?
10?????//方法代碼?
11???},?
12???…//其他方法?
13?}?
?2?function?class(sample,

?3????someProperty=sample;
?4????//其他屬性
?5?}?
?6?
?7?//通過指定prototype對(duì)象來實(shí)現(xiàn)類的成員定義?
?8?class.prototype={?
?9???someMethod:function(){?
10?????//方法代碼?
11???},?
12???…//其他方法?
13?}?
2?、構(gòu)造函數(shù)
??????
??
?1?function?class(sample,
){
?2?????????someProperty=sample;
?3?????????…//其他屬性
?4?????????//如果_init未定義,構(gòu)造函數(shù)將用原形方式繼續(xù)定義對(duì)象的方法,_init設(shè)置為true
?5?????????//用來判斷是否給原形賦予了任何方法,
?6?????????//內(nèi)部的函數(shù)只創(chuàng)建并賦值一次
?7?????????if(typeof?_init=="undefined"){
?8??????????????class.prototype={
?9??????????????????someMethod:function(){
10??????????????????????????//方法代碼?
11??????????????????????????????????},?
12???????????????????????…//其他方法???????????????
13?????????
14?????????}
15?????????_init=true;
16?????????};
17?????}

?2?????????someProperty=sample;
?3?????????…//其他屬性
?4?????????//如果_init未定義,構(gòu)造函數(shù)將用原形方式繼續(xù)定義對(duì)象的方法,_init設(shè)置為true
?5?????????//用來判斷是否給原形賦予了任何方法,
?6?????????//內(nèi)部的函數(shù)只創(chuàng)建并賦值一次
?7?????????if(typeof?_init=="undefined"){
?8??????????????class.prototype={
?9??????????????????someMethod:function(){
10??????????????????????????//方法代碼?
11??????????????????????????????????},?
12???????????????????????…//其他方法???????????????
13?????????
14?????????}
15?????????_init=true;
16?????????};
17?????}
???兩種模式都類似于傳統(tǒng)意義面向?qū)ο笳Z言中類的實(shí)現(xiàn),當(dāng)new一個(gè)對(duì)象時(shí),每個(gè)對(duì)象都擁有自己的屬性,同時(shí)方法是函數(shù)的引用。所以所有的函數(shù)多只創(chuàng)建一次,而每個(gè)對(duì)象擁有自己對(duì)象屬性實(shí)例。