Calculated/transient fields in JavaScript

javascript

Solution

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.

Problem

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.

Original source

Related problems