Implementing Pointers into JavaScript (Pt. 1)
Posted by JanWan
Last Updated: July 06, 2012
  1184

Implementing Pointers  into JavaScript


//! READ THIS:
//! Due to this post's publicity and the number of people asking if this is satire, or saying
//! that this is an awful idea, I feel the need to clarify. This was **never** intended to
//! actually be used, nor was it satirical. It was intended as a proof of concept to show what
//! Javascript is capable of.

var uid;
(function() {
 
var lastId = 0;
  uid
= function() {
   
return lastId++;
 
};
}());

global.$ = function(val) {
 
var id = uid();
 
global.$[id] = val;
 
Object.defineProperty(global.$, id, {
   
get: function() {
     
return val;
   
},
   
set: function(newVal) {
      val
= newVal;
     
return newVal;
   
},
    enumerable
: false
 
})
 
return id;
};

global.$.free = function(ptr) {
 
delete global.$[ptr];
};

Pointers are a powerful part of C, and they're so simple that it's not too hard to replicate them in other (powerful) languages. I made a pointer system not unlike C's in just a few lines of javascript.

The system lives inside a single global variable, $, which acts as both the address and dereferencing operator (I hope that's the correct terminology, I mean the unary * operator in C).

To create a pointer to a value, pass it to the $ function:

function returnFoo() {
  var foo = "foo";
 
return $(foo);
}
var foo = returnFoo();

foo will now be a number that acts like a memory address in C. You can prove it by logging it:

console.log("Address of foo:", foo);

To get the value stored in foo, use the dereferencing construct:

console.log("Value of foo:", $[foo]);

To change the value of foo, you still use the dereferencing construct:

$[foo] = "bar";

Proof the the value changed, but the address didn't:

console.log("Address of foo:", foo);
console
.log("New value of foo:", $[foo]);

Since pointers won't be picked up be the garbage collector due to their nature, you have to free them:

$.free(foo);

J.W.
PRODUCTION