簡體   English   中英

JavaScript中的計算/瞬態字段

[英]Calculated/transient fields in JavaScript

我正在嘗試使用OO JavaScript實現以下內容:

class Sample
{
  public int x {get; set;}
  public int y {get; set;}

  public int z
  {
    get {return x+y;}
  }
}

我無法理解如何在上面的類中實現屬性'z'。

你必須使用一個功能。 從ECMAScript第5版(ES5)開始,該函數可以是以正常非函數方式訪問的屬性的“getter”; 在此之前,您必須使用顯式函數調用。

這是ES5方式,使用definePropertyLive copy | 資源

function Sample()
{
    // Optionally set this.x and this.y here

    // Define the z property
    Object.defineProperty(this, "z", {
        get: function() {
            return this.x + this.y;
        }
    });
}

用法:

var s = new Sample();
s.x = 3;
s.y = 4;
console.log(s.z); // "7"

使用ES3(例如,早期版本):

function Sample()
{
    // Optionally set this.x and this.y here
}
Sample.prototype.getZ = function() {
    return this.x + this.y;
};

用法:

var s = new Sample();
s.x = 3;
s.y = 4;
console.log(s.getZ()); // "7"

請注意,您必須實際調用函數getZ() ,而ES5可以使其成為屬性訪問(只是z )。


請注意,JavaScript(尚未)具有class功能(盡管它是一個保留字,一個即將到來)。 您可以通過構造函數和原型來完成對象類,因為JavaScript是一種原型語言。 (好吧,它有點混合。)如果你開始進入層次結構,那么就會出現一些重要的,重復的管道。 有關詳細信息,請參閱Stack Overflow上的其他答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM