1

I have worked out a method to access an objects private properties by creating a method that returns those properties. However I would like to create a single function that can return any object property based on the string argument passed.

Here is an example of what I am trying to do:

function MyObj() {

    var myProp = 10;

    this.getProp = function( propName ) {

        return( propName ); // THIS IS WHERE I AM STUCK

    };


}

MyObj.prototype.getMyProp = function() {

    return this.getProp( 'myProp' );

};

var myObj = new MyObj();

console.log( myObj.getMyProp() );

As you can see from this example the string "myProp" is returned not the variable. I can't use this[propName] as I'm not in the right scope and I can't use the that/self technique to access the scope.

How do return an object property using a string?

McShaman
  • 3,627
  • 8
  • 33
  • 46

1 Answers1

3

One simple solution would be to wrap your private variables in an object like this:

function MyObj() {
    var privateVars = {
        myProp: 10
    };

    this.getProp = function( propName ) {
        return privateVars[propName];
    };
}

MyObj.prototype.getMyProp = function() {
    return this.getProp( 'myProp' );
};

var myObj = new MyObj();

console.log( myObj.getMyProp() ); // 10

Update: it appears that eval will work in this case, too, but I wouldn't recommend it:

function MyObj() {
    var myProp = 10;

    this.getProp = function( propName ) {
        return eval(propName);
    };
}

MyObj.prototype.getMyProp = function() {
    return this.getProp( 'myProp' );
};

var myObj = new MyObj();

console.log( myObj.getMyProp() ); // 10
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • Why wouldn't you recommend eval()? – McShaman May 05 '14 at 23:02
  • @McShaman Primarily because it's unsafe. Someone could easily write `myObj.getProp('myProp=20')` to mutate the private variables. Validating the property name (e.g. with `/^\w+$/.test(propName)`) would help, but I'd still go for the non-eval method unless I absolutely have to. See [Eval is Evil](http://blogs.msdn.com/b/ericlippert/archive/2003/11/01/53329.aspx) and [When is JavaScript's eval() not evil?](http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil). – p.s.w.g May 06 '14 at 14:56