0

I have associative arrays within an array that is created and passed as an argument within an object method like so:

myObject.method([
    {
        id: "mystring",
        myfun: function(g) {
                   return 'Value: ' + g.value + g.rows[0]['value'];
                   },
        a: "mysecondstring"
    },
        id: "mystring_a",
        myfun: function(g) {
                   return 'Value: ' + g.value + g.rows[0]['value'];
                   },
        a: "mysecondstring_a" 
    }]);

I have plenty of instances of this throughout my code and this works fine. The value of g is not declared beforehand. Now I want to change the myfun: function(g)... at run time, which requires that I declare my associative array before calling myObject.method(). Here is what I have tried:

myfun: new Function("g", "return 'Value: ' + g.value + " + my_dynamic_variable)

no good, then tried:

var fn = new Function("g", "return 'Value: ' + g.value + " + my_dynamic_variable)

with

myfun: fn(g)

and this

myfun: function(g) { return fn }

and this

var fn = function(g) { return eval('Value: ' + g.value + my_dynamic_variable) }

with

myfun: fn

Everything I have tried turns up null for g once the myfun code is executed. I'm guessing that variable g must be bound within the scope of myObject, and that I cannot define it outside of the myObject scope, but I am not certain.

Anyone know of a way to do this? Am I missing the mark here? Thanks!

4
  • This definitely looks like an XY problem. What's the real world use case? Maybe you need to think about a different data structure... Commented Aug 14, 2014 at 22:59
  • If you assign a function to the key its argument week be evaluated when it's called, e.g., you can reassign it to a new function the same way you assign it the first time. g is evaluated when the function is executed, it's a parameter. Commented Aug 14, 2014 at 23:04
  • Right, you just need to store that function, and pass a reference to it, var f = function(g){return 'Value: '+ g.value + g.rows[0].value}, then myfun: f Commented Aug 14, 2014 at 23:05
  • Now why didn't I think of that? Thanks everyone...geez...the answer seems so simple now you pointed it out... :) @elclanrs - it works! Much appreciated. If you post your comment as an answer, I will accept it. Commented Aug 14, 2014 at 23:23

1 Answer 1

1

You can store that function in a variable:

var f = function(g){return 'Value: '+ g.value + g.rows[0].value}

Then pass a reference to it:

myfun: f
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.