有了前面的基礎,我們現在來學習 JavaScript 中物件化編程的幾個關鍵語法。
with 為一組語句指定預設物件,常用來縮短重複書寫的程式碼。看看下面的例子,Math 被重複使用了多次:
x = Math.cos(3 * Math.PI) + Math.sin(Math.LN10); y = Math.tan(14 * Math.E);
改用 with 後,程式碼更短也更好讀:
with (Math) {
x = cos(3 * PI) + sin(LN10);
y = tan(14 * E);
}
this 回傳「當前」物件,在不同位置代表不同含義:在主程式中代表 window 物件;在 with 區塊中代表 with 指定的物件;在事件處理程式中代表發生事件的物件。常見用法是傳入表單以即時檢測輸入:
<input type="text" onchange="check(this.form)">
我們知道 Array()、Image() 等建構函式能產生變數,其實自己也能寫建構函式,一樣用 function,並在裡面用 this 定義屬性:
function <建構函式名> [(<參數>)] {
this.<屬性名> = <初始值>;
}
var <變數名> = new <建構函式名>[(<參數>)];
以下是一個蒐集瀏覽器詳細資訊的實用例子:
function Is() {
var agent = navigator.userAgent.toLowerCase();
this.major = parseInt(navigator.appVersion); // 主版本號
this.minor = parseFloat(navigator.appVersion); // 全版本號
this.ns = ((agent.indexOf('mozilla') != -1) &&
((agent.indexOf('spoofer') == -1) &&
(agent.indexOf('compatible') == -1))); // 是否 Netscape
this.ie = (agent.indexOf("msie") != -1); // 是否 IE
this.win = (agent.indexOf("win") != -1); // 是否 Windows
this.mac = (agent.indexOf("mac") != -1); // 是否 Macintosh
this.unix = (agent.indexOf("x11") != -1); // 是否 Unix
}
var is = new Is();
定義好 is 變數後,用 if (is.ns) 這樣的寫法就能方便地判斷瀏覽器資訊。
function myFriend(theName, gender, theAge, birthOn, theJob) {
this.name = theName;
this.isMale = (gender.toLowerCase() == 'male');
this.age = theAge;
this.birthday = new Date(birthOn);
this.job = theJob;
}
var Stephen = new myFriend('Stephen', 'Male', 18, 'Dec 22, 1982', 'Student');
這個例子不只示範了參數用法,也說明了不同屬性可用不同資料型別(字串、布林值、數字、日期),而且建構函式裡還能用建構函式來「建構」屬性。