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.
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 | sourceUsage:
With ES3 (e.g., earlier versions):
Usage:
Note that you have to actually make the function call
getZ(), whereas ES5 makes it possible to make it a property access (justz).Note that JavaScript doesn’t (yet) have a
classfeature (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.