How can i retrieve the reference to object containing a function from an input in the form objectReference["functionName"].
Example:
function aaa(param) {
var objectReference = /*..???...*/;
var functionName = /*...???..*/;
// Now expected result is that objectReference contains
// a reference to myObject, and functionName contains a
// string with name of function (implemented in myObject),
// so I can invoke it with objectReference[functionName]()
// after some manipulation.
}
var myObject = new SomeFunction();
aaa(myObject["myFunction"]);
Thank you
How can i retrieve the reference to object containing a function from an input in the form objectReference["functionName"].
Example:
function aaa(param) {
var objectReference = /*..???...*/;
var functionName = /*...???..*/;
// Now expected result is that objectReference contains
// a reference to myObject, and functionName contains a
// string with name of function (implemented in myObject),
// so I can invoke it with objectReference[functionName]()
// after some manipulation.
}
var myObject = new SomeFunction();
aaa(myObject["myFunction"]);
Thank you
Share Improve this question edited Mar 20, 2016 at 14:34 Nonemoticoner 6485 silver badges14 bronze badges asked Mar 20, 2016 at 13:48 AndreaAndrea 5661 gold badge6 silver badges23 bronze badges 1- your question is not quite clear, please elaborate further – Ammar Hasan Commented Mar 20, 2016 at 13:51
1 Answer
Reset to default 5You can't do either of the things you've listed. There are two separate things here:
Getting the
myObject
valueGetting the name of the property that that object uses to refer to the function
The value passed into aaa
in your code is just a reference to the function. The reference to the object is not passed into aaa
, nor is any information about what property the object used to refer to the function. Neither can be inferred or derived from the function reference itself. (The function may have a name, which could on modern JavaScript engines be access via its name
property, but that may well be different from the name of the property that the object used to refer to it.)
In order to do this, you have to pass them separately, either as discrete arguments:
aaa(myObject, "myFunction");
or as an object
aaa({obj: myObject, prop: "myFunction"});
In the latter case, aaa
might look like
function aaa(info) {
// Use info.obj and info.prop here
// The call would be
info.obj[info.prop]();
}
Another option, if you don't really need the object reference except for the purposes of making the call, is to use Function#bind
:
aaa(myObject["myFunction"].bind(myObject));
aaa
will receive a function reference that, when called, will call the original function with this
referring to myObject
. So aaa
can't actually get the object reference, but it can still make the call.