jaredrada
jaredrada

Reputation: 1150

avoid eval in this module

I have this module pattern that stores a bunch of vars. I want to create a single function that can return any given var (the real module has real functions- this is just a striped down version).

var myObject = (function() {
  var _savings = '100',
      _year = new Date().getFullYear(),
      _phone = '1-800-555-1234';

return {
  getMe: function(param) {
    return eval(param);
}

an example useage would be myObject.getMe('phone'); would poop out "1-800-555-1234"

I want to avoid the use of eval(), since its so evil.

Thanks!

Upvotes: 1

Views: 90

Answers (4)

McGarnagle
McGarnagle

Reputation: 102743

Doing this the object-oriented way, you could first create a prototype definition with the members *_savings*, *_year*, *_phone*. Add getMe to the prototype:

var myClass = function() {
    this._savings = '100',
    this._year = new Date().getFullYear(),
    this._phone = '1-800-555-1234';

    myClass.prototype.getMe = function(param) {
       return this[param]; 
    }
}

Then instantiate the object and run the method:

var myObject = new myClass();
console.log(myObject.getMe("_savings"));
  // "100"

Edited original answer (as Dancrumb points out, this does not work; they are private members, so inside the function getMe there is no way to see them).

Use bracket notation:

return this[param];

Upvotes: 0

Bob Davies
Bob Davies

Reputation: 2282

var myObject = {
    phone: '1-800-555-1234',
    year: new Date().getFullYear(),
    savings: 100,
    getMe: function(param) {
        return this[param];
    }
};
alert(myObject.getMe('phone'));

Upvotes: 0

Dancrumb
Dancrumb

Reputation: 27539

In javascript, object.field is equivalent to object["field"].

Now, the problem here is that you've created some private variables that don't belong to an object, so accessing them will be tricky.

An alternative approach would be this:

var myObject = (function() {
  var _privates = {
    savings: '100',
    year: new Date().getFullYear(),
    phone: '1-800-555-1234'
  };

return {
  getMe: function(param) {
    return _privates[param];
  }
}())

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Try the following:

var myObject = (function() {
    var data = {
        savings: '100',
        year: new Date().getFullYear(),
        phone: '1-800-555-1234'
    };
    return {
        getMe: function(param) {return data[param];}
    };
})();

Upvotes: 0

Related Questions