Javascript Pointers


In javascript, you can pass functions as parameters to functions meaning that you can either pass in anonymous functions or simply pointers to named functions without having to recreate those functions.

For instance, using the prototype.js library for AJAX requests, a function is expected as a handler for the response object.

You could do something like this:

new Ajax.request(someurl,{onComplete:function(rsp){alert.rsp.responseText});

or alternatively:

function dealwithit(rsp){
 alert (rsp.responseText);
}
new Ajax.request(someurl,dealwithit);

But what if you have a large and complex object that you want to pass into a function:

 supercomplex = new Object;
 supercomplex = $H({this:'can';get:'really',big:'if',you:'keep',on:'going'});
 function fun1(obj){
  obj.this = 'still can';
 }
 function fun2(obj){
  obj.get = 'dangerously';
 }
 fun1(supercomplex);
 fun2(supercomplex);

That's probably not a very good example, but essentially, when you are calling fun1, the supercomplex object is copied into the function, rather than actually being referenced directly. Any changes to the object in fun1 are not reflected in the supercomplex variable.

This is great for novice programmers because you always end up working with a local copy of the variable and you have to do a little bit of extra work to sync up the local copy with the parameter you are passing in.

It is a difficult problem to deal with however, when you are working with a large data set. Passing in a 512K object essentially means that you are using a megabyte of memory, and if you have nested function calls using the same parameter, the memory usage scales linearly and very quickly.

As far as I know, there is no way to reference a variable as a pointer natively within javascript. You can, however, use the "eval" function to simulate pointers, taking the above functions as an example:

collapsehide line numbers
Sample Code
  1 supercomplex = new Object;
  2 supercomplex = $H({this:'can';get:'really',big:'if',you:'keep',on:'going'});
  3 function fun1(obj){
  4  eval ('(' + obj + '[this] = \'still can\';'+')');
  5 }
  6 function fun2(obj){
  7  eval ('(' + obj + '[get] = \'dangerously\';'+')');
  8 }
  9 fun1(supercomplex);
 10 fun2(supercomplex);
Code ©SteveKallestad.com

It's not pretty, but it is an effective method for simulating pointers. Hopefully, I'll get back to this and produce some more useful examples of why you would want to do such a thing.



Join The Javascript Pointers Discussion