Reputation: 131
I am trying to code an object with a pointer-like behaviour. It is not meant to be a real pointer as used in other languages, but I need something that refers to a piece of data, so that I can pass that thing around and be sure it is always refering to the very same piece of data.
Consider the following code:
var Pointer = function (data) {
var instance = {};
instance.deref = function () { return data; };
return instance;
};
What I am doing now, is storing the data in the scope of the pointer instance.
My question is: Does storing the data in the scope of the pointer have any significant downsides in terms of speed when I have to move a bunch of pointers from one place to the other? Imagine a data structure where the data is represented by these pointers, all having a unique piece of data in their scope, and I have to manipulate the structure by moving pointers around.
Upvotes: 0
Views: 152
Reputation: 2128
Why all the trouble to wrap this in closures? Every object has pointer-like behavior. You won't get deep copies of objects unless you do the work to make one.
var x = {}, y;
x.data = "foo";
y = x;
y.data = "bar";
console.log(x.data) // "bar" because y and x are references to the same object
Really, the only major behavior that differentiates JavaScript references from C-style pointers is the lack of pointer arithmetic or casting a pointer to/from an integer. You can definitely shuffle references to objects around in your data structure without creating copies of the objects being referenced.
In the code above, if we're being precise in our language, x and y are not objects, x and y are references (very similar to pointers) to objects. When we assign an empty object to x, x now refers to (points at) an empty object. We later set y to refer to (point at) the same object as x.
Upvotes: 3