所謂構(gòu)造函數(shù),就是通過這個(gè)函數(shù)生成一個(gè)新對(duì)象(object)。
function Test(){//大寫,以區(qū)分普通函數(shù) this.x = 10;}var obj = new Test();alert(obj.x); //彈出 10;可以使用 new 運(yùn)算符結(jié)合像 Object()、Date() 和 Function() 這樣的預(yù)定義的構(gòu)造函數(shù)來創(chuàng)建對(duì)象并對(duì)其初始化。面向?qū)ο蟮木幊唐鋸?qiáng)有力的特征是定義自定義構(gòu)造函數(shù)以創(chuàng)建腳本中使用的自定義對(duì)象的能力。創(chuàng)建了自定義的構(gòu)造函數(shù),這樣就可以創(chuàng)建具有已定義屬性的對(duì)象。下面是自定義函數(shù)的示例(注意 this 關(guān)鍵字的使用)。
function Circle (xPoint, yPoint, radius) { this.x = xPoint; // 圓心的 x 坐標(biāo)。 this.y = yPoint; // 圓心的 y 坐標(biāo)。 this.r = radius; // 圓的半徑。}調(diào)用 Circle 構(gòu)造函數(shù)時(shí),給出圓心點(diǎn)的值和圓的半徑(所有這些元素是完全定義一個(gè)獨(dú)特的圓對(duì)象所必需的)。結(jié)束時(shí) Circle 對(duì)象包含三個(gè)屬性。下面是如何例示 Circle 對(duì)象。
var aCircle = new Circle(5, 11, 99);使用構(gòu)造器函數(shù)的優(yōu)點(diǎn)是,它可以根據(jù)參數(shù)來構(gòu)造不同的對(duì)象。 缺點(diǎn)是構(gòu)造時(shí)每個(gè)實(shí)例對(duì)象都會(huì)生成重復(fù)調(diào)用對(duì)象的方法,造成了內(nèi)存的浪費(fèi)。
function Test(name){ this.occupation = "coder"; this.name = name; this.whoAreYou = function(){ return "I'm " + this.name + "and I'm a " + this.occupation; }}var obj = new Test('trigkit4');//利用同一個(gè)構(gòu)造器創(chuàng)建不同的對(duì)象var obj2 = new Test('student');obj.whoAreYou();//"I'm trigkit4 and I'm a corder"obj2.whoAreYou();//"I'm student and I'm a corder"依照慣例,我們應(yīng)該將構(gòu)造器函數(shù)的首字母大寫,以便顯著地區(qū)別于一般的函數(shù)。
新聞熱點(diǎn)
疑難解答
圖片精選