More Javascript Fun. Private variables.

So I have a class in C# that looks like this:

public class Unit{
    private int _Id;
    public Unit(int Id){
        _Id = Id;
    public string WhoAmId(){
       return _Id.ToString();

So you want to see what that would look like in JavaScript?

var Unit = (function () {
//This function is basically treated as an object. function Unit(id) { this._id = id; }
//This is how we extended Unit to have the new function. Unit.prototype.WhoAmId = function () { return this._id.toString(); };
//If you are paying attention here, this is really a function,
//but it acts like a class. return Unit; })(); //These last () return the function that now acts like a class,
// by executing the wrapper function.

So to implement just call

var newUnit = new Unit(5);

//prototypes are functions. So you still need to call then like a function. alert(newUnit.WhoAmId());

Enjoy playing with JavaScript.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.