Khalid
Khalid

Reputation: 4808

is there a way to call a function dynamically witout the use of eval

I have a javascript object containing many functions like this

function obj()
{
            this.test1_func = function()
            {
                return "This is function 1";
            }
            this.test2_func = function()
            {
                return "This is function 2";
            }
            this.test3_func = function()
            {
                return "This is function 3";
            }
            // and many other functions like test"x"_func ...
}

No inside the definition of the object, I define properties like this

    Object.defineProperty(this, 'test1', 
    {
        get : function() 
        { 
            return this.test1_func();
        }  
    });

    Object.defineProperty(this, 'test2', 
    {
        get : function() 
        { 
            return this.test2_func();
        }  
    });

    Object.defineProperty(this, 'test3', 
    {
        get : function() 
        { 
            return this.test3_func();
        }  
    });

is there a way you can have the properties names in an array and a function that defines all of them ?? I made a function that works fine, but I used eval and I want to know if is there a way you can do it without eval

this.defineProp = function (prop)
{
  for(key in prop)
  {
     Object.defineProperty(this,prop[key],{ get : function() { return eval("this." + prop[key] + "_func();"); } });
  }
}

Upvotes: 0

Views: 57

Answers (3)

Ben Aston
Ben Aston

Reputation: 55789

Why not simply expose the functions via another function?

obj.prototype.get = function(testName) {
  return this[testName + _func];
};

So instead of:

obj.test1();

You need:

obj.get('test1')();

Upvotes: 0

Hattan Shobokshi
Hattan Shobokshi

Reputation: 687

Try this:

this.defineProp = function (prop)
{
  for(key in prop)
  {
     Object.defineProperty(this,prop[key],{ get : function() { return this[prop[key]+"_func"](); } });
  }
}

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102793

You should be able to use the square-bracket notation:

Object.defineProperty(this,prop[key],{ get : function() { return this[prop[key] + "_func"](); } });

Or more concisely:

Object.defineProperty(this,prop[key],{ get: this[prop[key] + "_func"]; } });

Upvotes: 2

Related Questions