所謂構造函數(shù),就是通過這個函數(shù)生成一個新對象(object)。
function Test(){//大寫,以區(qū)分普通函數(shù) this.x = 10;}var obj = new Test();alert(obj.x); //彈出 10;可以使用 new 運算符結合像 Object()、Date() 和 Function() 這樣的預定義的構造函數(shù)來創(chuàng)建對象并對其初始化。面向對象的編程其強有力的特征是定義自定義構造函數(shù)以創(chuàng)建腳本中使用的自定義對象的能力。創(chuàng)建了自定義的構造函數(shù),這樣就可以創(chuàng)建具有已定義屬性的對象。下面是自定義函數(shù)的示例(注意 this 關鍵字的使用)。
function Circle (xPoint, yPoint, radius) { this.x = xPoint; // 圓心的 x 坐標。 this.y = yPoint; // 圓心的 y 坐標。 this.r = radius; // 圓的半徑。}調用 Circle 構造函數(shù)時,給出圓心點的值和圓的半徑(所有這些元素是完全定義一個獨特的圓對象所必需的)。結束時 Circle 對象包含三個屬性。下面是如何例示 Circle 對象。
var aCircle = new Circle(5, 11, 99);使用構造器函數(shù)的優(yōu)點是,它可以根據(jù)參數(shù)來構造不同的對象。 缺點是構造時每個實例對象都會生成重復調用對象的方法,造成了內存的浪費。
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');//利用同一個構造器創(chuàng)建不同的對象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"依照慣例,我們應該將構造器函數(shù)的首字母大寫,以便顯著地區(qū)別于一般的函數(shù)。
|
新聞熱點
疑難解答