How to change dynamically the js code?

194 Views Asked by At

How to replace a JS function's code at runtime? (the same functionality as C++ function pointers)

I have tried eval(), but when one of the parameters contains a byte value like 13 or 10 it throws an error.

I understand from this that eval is actually evaluating every lexical atom and replaces them with their content.

These are some example files to illustrate the functionality I'm looking for:


File 1: index.html

xmlhttp=new XMLHttpRequest();   
xmlhttp.open("GET","dynamic_code.php",false);
xmlhttp.send();
var dynamic_code=xmlhttp.responseText;
function dynamic_function (){
    eval(dynamic_code)
}
dynamic_function ()

File 2: dynamic_code.php

some_file=new XMLHttpRequest(); 
some_file.open("GET","some_file.txt",false);
some_file.send();
var some_file_content=some_file.responseText;
alert(some_file_content);

File 3: some_file.txt

line1
line2
line3

ERROR returned by browser:

> Uncaught exception: SyntaxError: at line 2, column 0: expected
> expression, got '<' Error thrown at line 12, column 4 in
> dynamic_function() in http://my_ip/dummy/index.html:
>     eval(dynamic_code) called from line 15, column 0 in http://my_ip/dummy/index.html:
>     dynamic_function ()
1

There are 1 best solutions below

0
On

This is not the same functionality as C++ function pointers :-)

This'd be the same:

function someFunc() {
}

function otherFunc(f) {
    f();
}

otherFunc(someFunc);

And it works :) Javascript has first class functions. (Which C++ emulates with function pointers.)

What you're trying to do would be this in C++:

void someFunc(f) {
    eval(f); // doesn't exist of course
}

someFunc("void otherFunc() {}");

Now that the truth has been established, let's come back to your problem.

What you're looking for is called JSONP. It's a technique that consists of injecting a script tag in the browser. When the script is injected, the javascript code inside is executed. The main reason why it's used is because it works cross-domain, you don't need XHR for this. But you can also use it for your use-case.