1

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 ()
WooCaSh
  • 5,180
  • 5
  • 36
  • 54
root
  • 25
  • 4
  • Is `dynamic_code.php` being served properly? Try outputting the contents of `dynamic_code` via `console.log` or `alert` before the eval. – Deestan Oct 23 '12 at 09:22
  • i thin u are making it more complicated than it should be there should be no such scenario to replace the code of a JS function simply make two or three parts in your JS function calling on certain values of a variable , just pass this variable in response , and your desired part will be activated – Hussain Akhtar Wahid 'Ghouri' Oct 23 '12 at 10:43

1 Answers1

0

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.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116