Evaluating arbitrary JS inside a scope

UPDATE

This was just a quick experiment to see if I could do this using some ideas "stolen" from StackOverflow. Since then, I actually started to implement the code for my use case and there's a better solution On my Github and this article will be updated to match that in "the near future".

Here we have a normal JS object that stands in for the scope of our evaled code.

Read only properties do require a little extra work to add them to the object and they don't appear as ordinary fields (e.g. in a console.log

Here's the actual evaluation function.

The function constructor both does the evaluation without an explicit call to eval (just in case you were wondering where it was).

It also side-steps the "strict-mode" prohibition on using with. The with is necessary to allow us to access properties within scopeObject as though they were any normal JS scope (i.e. without prefixing them with this.).

To read values from the scope, we can just reference them by name.

You can also write existing values with a "straight assignment"

To add values to the scope they must be prefixed with this

Read only properties can be read just like normal properties

Read only properties cannot be changed