JavaScript 支援物件化編程。透過 with、this 與自訂建構函式,可以把資料與行為組織得更清楚。
with 可以為一組語句指定預設物件,減少重複前綴。
with (Math) {
x = cos(3 * PI) + sin(LN10);
y = tan(14 * E);
}
不過,with 容易讓程式碼變得難以追蹤,因此不建議在現代開發中頻繁使用。
this 代表目前物件。在不同情境下,this 的指向可能不同:
可以使用 function 建立自己的建構函式,再用 new 建立物件。
function Is() {
var agent = navigator.userAgent.toLowerCase();
this.major = parseInt(navigator.appVersion, 10);
this.ie = agent.indexOf("msie") != -1;
}
var is = new Is();
建立後,就可以透過 is.ie、is.major 等屬性取得瀏覽器資訊。
function myFriend(theName, gender, theAge, birthOn, theJob) {
this.name = theName;
this.age = theAge;
this.birthday = new Date(birthOn);
this.job = theJob;
}
var Stephen = new myFriend("Stephen", "Male", 18, "Dec 22, 1982", "Student");
透過建構函式,可以把多個相關資料與行為集中在同一個物件中,讓程式碼更易維護。