3

I am trying to achieve something like the following using OO JavaScript:

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

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

I could not understand on how to implement property 'z' in above class.

user203687
  • 6,875
  • 12
  • 53
  • 85
  • 4
    That looks like Java, not JavaScript. Are you saying you want to implement something like that in JavaScript? (Also the syntax for the values for "x" and "y" is unfamiliar.) – Pointy Jul 07 '12 at 15:45
  • 1
    Looks more like C# to me. But however, how did you implement the rest of the class? – Niko Jul 07 '12 at 15:46
  • @Niko yes probably you're right :-) – Pointy Jul 07 '12 at 15:46
  • The code is in C# just to explain what I am looking for in JavaScript (not Java). – user203687 Jul 07 '12 at 16:05

1 Answers1

5

You have to use a function. As of ECMAScript 5th edition (ES5), that function can be a "getter" for a property that you access in the normal non-function way; prior to that you have to use an explicit function call.

Here's the ES5 way, using defineProperty: Live copy | source

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;
        }
    });
}

Usage:

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

With ES3 (e.g., earlier versions):

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

Usage:

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

Note that you have to actually make the function call getZ(), whereas ES5 makes it possible to make it a property access (just z).


Note that JavaScript doesn't (yet) have a class feature (although it's a reserved word and one is coming). You can do classes of objects via constructor functions and prototypes, as JavaScript is a prototypical language. (Well, it's a bit of a hybrid.) If you start getting into hierarchies, there starts to be some important, repetitive plumbing. See this other answer here on Stack Overflow for more about that.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875