2

I'm trying to create a javascript expression parser, able to parse an expression and get the declared variables in its body, without executing the function:

function test(expressionFn) {
  var expression = getExpression(expressionFn);
  // get value expression.expressionRight in scope
  // not work -> var valueRigthInScope = expressionFn.prototype.constructor[[[Scopes]]][expression.expressionRight];
  console.log(expressionFn.prototype); // see ".constructor[[[Scopes]]]" in debug tools [F12]
}

function getExpression(expressionFn) {
  var strAfterReturn = expressionFn.toString().split("return")[1].trim();
  let strExpression = strAfterReturn.split(";")[0].split(" ");
  return {
      expressionLeft: strExpression[0],
      operator: strExpression[1],
      expressionRight: strExpression[2]
  };
}

function start(){
 var myValue = "This is value!";
 test(function(x) { return x.prop1 == myValue; });
}

start();
<h1>See console</h1>

Example in JsFiddle.

But I can not access the scope of the function to get the value of the variable myValue, for example.

In the Google Chrome console I managed through the function to get the scope where the variable myValue is declared, but I can not access that same scope in javascript.

Follows the image of the Google Chrome console:

enter image description here

How can I access [[Scopes]] in the image?

Fernando Leal
  • 9,875
  • 4
  • 24
  • 46
  • 4
    You cannot programmatically access scope from within JavaScript. This is impossible by design, and the output you see is strictly available within the debugging tools of the console. – Patrick Roberts Jul 25 '17 at 21:02
  • you can't. you would need to `eval()` the code in the same local scope as your desired var is defined. Also, functions can have multiple returns and nested functions, so your "parser" is very fragile and limited. – dandavis Jul 25 '17 at 21:02
  • if you want to make myValue accessible from OUTSIDE the function .. use `window.myValue = 'whatever'` – Zak Jul 25 '17 at 21:02
  • 3
    [This is a XY problem.](http://xyproblem.info) What do you actually want to achieve? Why are you parsing JavaScript functions? – idmean Jul 25 '17 at 21:10
  • @PatrickRoberts, So the answer to my question is 'no', is it not possible to access the Scope object via javascript? Or alternatively? Just to clarify, what I am trying to implement with this is an analyzer that can get the expression information, similar to the [Lambda Expression](https://learn.microsoft.com/pt-br/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions). My current implementation state covers much better parse of various function formats and also has a more closed format of supported functions because I use this with Typescript. – Fernando Leal Jul 26 '17 at 11:40

0 Answers0