0

I'm trying to find a way to "extract" all internally defined variables within a function passed to another function. This looks to be impossible, but something tells me that I haven't tried all possible solutions. I need to get a references to the callerFunction's internalVariable inside the tryReadInternalVarvalue

The code is simplified, but the similar code already works with the JavaScript array .findIndex-method - it doesn't care about scopes and the strict mode. In the code sample below, exactly in the tryReadInternalVarValue I need to find which value was used against my targetObj.title to match. I have control over my targetObj.

const tryReadInternalVarValue = function(functionRef) {
    const targetObj = {
        title: "World"
    };

    const isMatch = functionRef(targetObj);
    if (!isMatch) {
        throw Error(``);
    }

    // Here must go my code to "extract" all the functionRef internal variables
    // naive console.log(functionRef[["Scopes"]]["Closure"]["internalVariable"]) ==> "Hello"

    // Is there a way (like Reflection) to figure out which value 
    // was used against the targetObj.title to compare HERE?
    // How I would extract the "Hello" value out of the passed function's
    // internally declared variable in STRICT MODE?
    return isMatch;
}

const callerFunction = function() {
    const internalVariable = "Hello";
    const meCallingThisFunction = function (passingThisObject) {
        return passingThisObject.title === internalVariable;
    }

    return tryReadInternalVarValue(meCallingThisFunction)
}

console.log(callerFunction());

I tried:

  • arguments.caller - in strict mode it's not available
  • functionRef.call(new Proxy({}, {get(target, p, receiver) { console.log()}}), targetObj)
MMS
  • 90
  • 7

1 Answers1

1

This looks to be impossible

…and it absolutely is. Closed-over variables are private, you cannot access them from outside.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375