javascript - 严格模式。从引用的函数中提取内部定义的变量
问题描述
我试图找到一种方法来“提取”传递给另一个函数的函数中的所有内部定义变量。这看起来是不可能的,但有些事情告诉我,我还没有尝试所有可能的解决方案。我需要在 tryReadInternalVarvalue 中获取对 callerFunction 的 internalVariable 的引用
代码被简化了,但类似的代码已经在 JavaScript 数组 .findIndex-method 上工作了——它不关心范围和严格模式。在下面的代码示例中,正是在 tryReadInternalVarValue 中,我需要找到用于匹配我的 targetObj.title 的值。我可以控制我的 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());
我试过了:
- arguments.caller - 在严格模式下不可用
- functionRef.call(new Proxy({}, {get(target, p, receiver) { console.log()}}), targetObj)
解决方案
这看起来是不可能的
……绝对是。封闭变量是私有的,您不能从外部访问它们。