0

I have a class (constructor function) User

function User(id) {
    this._id = id;
}

from which I make my objects like user

var user = new User(9);

And I want to write getter function for this user object, but not actually particularly for it, but rather for all objects created by my constructor function User.

I though this should work but it isn't

Object.defineProperty(User, 'id', {
    get: function() {
        console.info('Using getter..');
        return this._id;
    },
    // set:function(val) { alert('set value'); }
});

var user = new User(9);

console.info(user.id); // gives undefined

I figured it's because User is a constructor function, and not actually an object, defining getter function like that doesn't work. Is it still possible some other way?

laggingreflex
  • 32,948
  • 35
  • 141
  • 196
  • 1
    The way you have it set up, the _id property is public and accessible. Adding a getter function is superfluous. – Femi Mar 05 '14 at 05:11
  • More about prototype here.http://stackoverflow.com/a/16063711/1641941 a link to a pattern that can simulate protected memebers is at the end – HMR Mar 05 '14 at 05:20

2 Answers2

1

Figured it out. Just had to move the getter definition inside the constructor function itself, from where I can correctly use this.

function User(id) {
    this._id = id;

    Object.defineProperty(this, 'id', {
        get: function() {
            console.info('Using getter..');
            return this._id;
        },
        // set:function(val) { alert('set value'); }
    });
}
laggingreflex
  • 32,948
  • 35
  • 141
  • 196
0

The way you have it set up, the _id property is public and accessible. Adding a getter function is superfluous.

To properly hide the inner variable to that object, you need to:

function User(id) {
    var _id = id;

    this.getID = function(){
        return _id;
    }
}

If you don't properly hide the variable, why bother writing a getter; The way you have it now, you can just do console.info((new User(12))._id). If you attach a variable to the this pointer, it makes it a public property of that class.

Femi
  • 1,332
  • 9
  • 20