JavaScript中的计算/瞬态字段

use*_*687 3 javascript

我正在尝试使用OO JavaScript实现以下内容:

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

  public int z
  {
    get {return x+y;}
  }
}
Run Code Online (Sandbox Code Playgroud)

我无法理解如何在上面的类中实现属性'z'.

T.J*_*der 5

你必须使用一个功能.从ECMAScript第5版(ES5)开始,该函数可以是以正常非函数方式访问的属性的"getter"; 在此之前,您必须使用显式函数调用.

这是ES5方式,使用defineProperty:Live 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;
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

用法:

var s = new Sample();
s.x = 3;
s.y = 4;
console.log(s.z); // "7"
Run Code Online (Sandbox Code Playgroud)

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

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

用法:

var s = new Sample();
s.x = 3;
s.y = 4;
console.log(s.getZ()); // "7"
Run Code Online (Sandbox Code Playgroud)

请注意,您必须实际进行函数调用getZ(),而ES5可以使其成为属性访问(仅z).


请注意,JavaScript还没有(还)有一个class功能(虽然它是一个保留字,一个即将到来).您可以通过构造函数和原型来完成对象类,因为JavaScript是一种原型语言.(好吧,它有点混合.)如果你开始进入层次结构,那么就会出现一些重要的,重复的管道.有关详细信息,请参阅Stack Overflow上的其他答案.