DIV CSS 佈局教程網

JavaScript 物件化編程:with、this 與自訂建構函式
編輯:JavaScript基礎知識     

JavaScript 支援物件化編程。透過 with、this 與自訂建構函式,可以把資料與行為組織得更清楚。

with 語句

with 可以為一組語句指定預設物件,減少重複前綴。

with (Math) {
  x = cos(3 * PI) + sin(LN10);
  y = tan(14 * E);
}

不過,with 容易讓程式碼變得難以追蹤,因此不建議在現代開發中頻繁使用。

this 物件

this 代表目前物件。在不同情境下,this 的指向可能不同:

  • 在主程式中,通常代表 window。
  • 在事件處理器中,通常代表觸發事件的物件。
  • 在物件方法中,通常代表呼叫該方法的物件。

自訂建構函式

可以使用 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");

透過建構函式,可以把多個相關資料與行為集中在同一個物件中,讓程式碼更易維護。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved