Javascript Jems - Self Modifying Code
Written by Ian Elliot   
Thursday, 18 April 2019
Article Index
Javascript Jems - Self Modifying Code
Eval

String To Function Using Eval

Before you get worried because you have heard that eval is evil - it isn't. eval is one of the more powerful features of JavaScript and many an interpreted language. As it is powerful it is capable of misuse and if used to process user or server input then it can be used to get the program to do things you never dreamed of. However this doesn't mean you can't use eval internally in a safe way. 

The eval function accepts a string of JavaScript statements and executes them as if they were within your program.

One of the problem is that programmers will often say such-and-such an instruction is dangerous - without saying why. In the case of eval the only danger is that some outside agent will feed in an expression that evaluates to something that you didn't expect or would have allowed had you expected it.

In other words if the string to be evaluated has its origins in anyway influenced by the outside world then you have to make sure that they outside world doesn't manage to feed it a string that does something evil. You can do this by checking that the string to be evaluated is limited in some way - usually referred to as sanitising the input or you can simply find some less powerful way to achieve the same result i.e. don't use eval. 

If however the string to be evaluated originates within your program and is 100% under control then what could possibly go wrong?

So to convert a string to a function you simply use:

myString=myString.replace("1","2");
eval("myFunc2=" + myString);
myFunc2();

Which displays the alert box "MyFunc2". From this point on in the program myFunc2 behaves like a standard Function object. Notice that its scope is determined by the scope of the myFunc2 variable and the function only exists after the eval operation - i.e. there is no function hoisting. 

This completes the “round-trip” in the sense that you can now convert a function to a string, modify it and convert it back to a function or you can simply put a function together as a string as the program runs and convert it to a function when you want to use it.

 

Banner

 

This gives you the power to write self-modifying code of arbitrary complexity and the same tricks can be used to modify object methods just as easily.

Simpler self modification

However it is worth mentioning that some of the most useful forms of self modification are much simpler and much safer than the general scheme outlined above.

 

jemsicon

 

Consider the following:

 

myfunc=function(){
 if(browser=="IE") {
  alert("Browser 1");
 } else  {
  alert("Browser 2");
 }
};

 

In this case myfunc has to deal with the possibility that it might be run on one of two types of browser and what it has to do is browser specific. It does this using a simple if statement but each time the function is called the selection has to be made even though once loaded the browser type cannot change.

That is, each time myfunc is called it has to check the state of the browser variable even though it can’t have changed since the last time it was used.

We can make this all much more efficient by simply redefining the function depending on which version of the browser it finds itself in:

myfunc=function(){
 if(browser=="IE"){
  myfunc=function() {alert("Browser 1")};
 } else {
  myfunc=function() {alert("Browser 2")};
 };
 myfunc();
};

Notice that the system is sophisticated enough to buffer the function definition so that changing it mid-way through its execution has no effect. However, the new call to the function at the end of the modification does run the new function.

If you find this confusing simply compare the function’s definition before and after it has been run:

var browser="IE";
alert(myfunc);
myfunc();
alert(myfunc);

Before the first call the function is as listed above complete with the if statement. After the first call it simply reads:

function() {alert("Browser 1")};

and no test is made to see which browser it is being run in until it is started afresh in possibly a different browser.

This is a very attractive idea. Creating self modifying functions in this way is a safe thing to do and it is used in a number of JavaScript libraries.

However self-modifying code is dangerous and often over complex– use it with great care and not very often.

 

 

 

Related Articles

Javascript Jems - First class functions

Chaining - Fluent Interfaces In JavaScript

JavaScript Objects With Value - valueOf and toString

Now available as a book from your local Amazon.

JavaScript Jems:
The Amazing Parts

kindlecover

JavaScript Jems - Functional And Not Quite Functional

Original drafts of chapters.

Contents

  1. JavaScript Patterns 
    Why JavaScript is a Jem
  2. Objects with Values in JavaScript*
  3. Private Functions In JavaScript
  4. Chaining - Fluent Interfaces In JavaScript*
  5. Active Logic, Truthy and Falsey*
  6. The Confusing Comma In JavaScript*
  7. Self Modifying Code*
  8. Lambda expressions
  9. Meta Programming Using Proxy
  10. Master JavaScript Regular Expressions
  11. The Function Approach To Programming

<ASIN:1871962579>

<ASIN:1871962560>

<ASIN:1871962501>

<ASIN:1871962528>

espbook

 

Comments




or email your comment to: comments@i-programmer.info

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

 

 



Last Updated ( Thursday, 13 June 2019 )