简体   繁体   中英

Get object reference, and function name

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

You can't do either of the things you've listed. There are two separate things here:

  1. Getting the myObject value

  2. Getting 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM