跳轉到內容

JavaScript/保留字/this

來自華夏公益教科書,開放的書籍,開放的世界
上一頁:synchronized 保留字 下一頁:throw

Thethis關鍵字

[編輯 | 編輯原始碼]

Thethis關鍵字允許方法讀取和寫入該物件例項的屬性變數。

以下示例使用首字母大寫來表示PopMachine()以幫助表明該物件需要使用new關鍵字建立。您可以使用new關鍵字與任何函式一起建立物件,但是如果您只使用new用於此目的的函式,並透過用首字母大寫來命名這些函式來標記它們,那麼跟蹤您的操作會容易得多。

示例 1
function PopMachine() {
  this.quarters = 0;
  this.dollars = 0;
  this.totalValue = function () {
    var sum = this.quarters*25 + this.dollars*100;
    return sum;
  }
  this.addQuarters = function (increment) {
    this.quarters += increment;
  }
  this.addDollars = function (increment) {
    this.dollars += increment;
  }
}
function testPopMachine() {
  var popMachine = new PopMachine();
  popMachine.addQuarters(8);
  popMachine.addDollars(1);
  popMachine.addQuarters(-1);
  alert("Total in the cash register is: " + popMachine.totalValue());
}
testPopMachine();

請注意,上述方法效率低下,如果需要建立一個嚴肅的 JavaScript 類,則必須先學習原型。

示例 2
money = {
    'quarters': 10,
    'addQuarters': function(amount) {
        this.quarters += amount;
    }
};
money.addQuarters(10);

現在硬幣總數為二十個。

上一頁:synchronized 保留字 下一頁:throw
華夏公益教科書