From 197c8469f458ee8977b11be95f3f7cda21b580a6 Mon Sep 17 00:00:00 2001 From: Andy Preston Date: Sun, 21 Apr 2024 12:58:12 +0100 Subject: [PATCH] New article about eval and scopes for JS --- views/arbitrary-js.webc | 80 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 views/arbitrary-js.webc diff --git a/views/arbitrary-js.webc b/views/arbitrary-js.webc new file mode 100644 index 0000000..f802487 --- /dev/null +++ b/views/arbitrary-js.webc @@ -0,0 +1,80 @@ +--- +title: "Evaluating arbitrary JS inside a scope" +tags: javascript +date: "2024-04-21" +--- +
+ +

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

+