functionSpecialArray(){varvalues=newArray();values.push.apply(values,arguments);values.toPipedString=function(){returnthis.join("|");};returnvalues;}varcolors=newSpecialArray("red","blue","green");alert(colors.toPipedString());//"red|blue|green"關(guān)于javascript中的寄生構(gòu)造函數(shù)模式,我覺(jué)得他和工廠(chǎng)模式其實(shí)就是一樣的,只不過(guò)在寫(xiě)法上用了new這種構(gòu)造函數(shù)的寫(xiě)法,用意是要在不擴(kuò)展原生構(gòu)造函數(shù)的情況下自定義一個(gè)擴(kuò)展型的構(gòu)造函數(shù)。既然是擴(kuò)展原生的構(gòu)造函數(shù),那么用起來(lái)當(dāng)然要像個(gè)構(gòu)造函數(shù),于是就用了new這種構(gòu)造函數(shù)的寫(xiě)法。顯式的return重寫(xiě)了調(diào)用構(gòu)造函數(shù)時(shí)返回的值,所以new不new其實(shí)最后的結(jié)果沒(méi)有影響,那么寫(xiě)只是為了用起來(lái)像構(gòu)造函數(shù)。之所以要有這個(gè)模式是因?yàn)闃?gòu)造函數(shù)模式只能new出一個(gè)Object類(lèi)型,不能夠new出一個(gè)比如Array,類(lèi)似這樣是行不通的:functionSpecialArray(){this=newArray();this.push.apply(this,arguments);this.toPipedString=function(){returnthis.join("|");};}varcolors=newSpecialArray("red","blue","green");alert(colors.toPipedString());//報(bào)錯(cuò):Invalidleft-handsideinassignment大家看看我理解的對(duì)嗎?
javascript中的寄生構(gòu)造函數(shù)模式其實(shí)就是為了讓工廠(chǎng)模式用起來(lái)像構(gòu)造函數(shù)一樣而刻意為之的嗎?
慕田峪4524236
2019-04-08 11:16:51