Are there pointers in javascript?
No, JS doesn't have pointers.
Objects are passed around by passing a copy of a reference. The programmer cannot access any C-like "value" representing the address of an object.
Within a function, one may change the contents of a passed object via that reference, but you cannot modify the reference that the caller had because your reference is only a copy:
var foo = {'bar': 1};
function tryToMungeReference(obj) {
obj = {'bar': 2}; // won't change caller's object
}
function mungeContents(obj) {
obj.bar = 2; // changes _contents_ of caller's object
}
tryToMungeReference(foo);
foo.bar === 1; // true - foo still references original object
mungeContents(foo);
foo.bar === 2; // true - object referenced by foo has been modified
How to create a pointer in JavaScript
There are no pointers in the JavaScript language.
Every variable that contains an Object
is actually an opaque reference to that object.
Within the interpreter that reference will take the form of a pointer, but the value of that pointer is not accessible to you.
How to simulate pointers in JavaScript?
Needless to say, but JavaScript does not have a general mechanism to pass arguments by reference.
There can be some confusion around the term "reference", as in JavaScript one can pass objects to functions -- which are references -- but this is a call-by-value mechanism. Call-by-reference really means that the parameter variable is an alias for the caller's variable, such that assigning to that alias is equivalent to assigning to the caller's variable. Except for some very particular situations (like the arguments
exotic object in non-strict mode, or the export
mechanism, or the var
link with the window
object, none of which helps you in your case in a best practice way), there is no such variable-aliasing mechanism in JavaScript.
Here is an example on how to "exploit" the effect of var
in a browser context, in non-strict mode:
function modify(ref) {
// Using the fact that global `var` variables are aliases
// for properties on the global object
// (This is not considered good practice)
globalThis[ref] = globalThis[ref] + 1;
}
var a = 1;
modify("a"); // We pass a reference to `a`
console.log(a);
Pointers in JavaScript?
Since JavaScript does not support passing parameters by reference, you'll need to make the variable an object instead:
var x = {Value: 0};
function a(obj){ obj.Value++;}
a(x);document.write(x.Value); //Here i want to have 1 instead of 0
Is there a better way to simulate pointers in JavaScript?
Since the only thing you're using the pointer for is to dereference it to access another variable, you can just encapsulate it in a property.
function createPointer(read, write) {
return { get value() { return read(); }, set value(v) { return write(v); } };
}
To create a pointer, pass the accessor methods which read and write the variable being pointed to.
var i;
var p = createPointer(function() { return i; }, function(v) { i = v; });
// p is now a "pointer" to i
To dereference a pointer, access its value. In other words, where in C you would write *p
here you write p.value
.
i = "initial";
alert(p.value); // alerts "initial"
p.value = "update";
alert(i); // alerts "update"
p.value += "2";
alert(i); // alerts "update2"
You can create multiple pointers to the same variable.
var q = createPointer(function() { return i; }, function(v) { i = v; });
// q is also a "pointer" to i
alert(q.value); // alerts "update2"
q.value = "written from q";
alert(p.value); // alerts "written from q"
You can change what a pointer points to by simply overwriting the pointer variable with another pointer.
var j = "other";
q = createPointer(function() { return j; }, function(v) { j = v; });
// q is now a "pointer" to j
You can swap two variables through pointers.
function swap(x, y) {
var t = x.value;
x.value = y.value;
y.value = t;
}
Let's swap the values of i
and j
by using their pointers.
swap(p, q);
alert(i); // alerts "other"
alert(j); // alerts "written from q"
You can create pointers to local variables.
function example() {
var myVar = "myVar as local variable from example";
var r = createPointer(function() { return myVar; }, function(v) { myVar = v; });
swap(p,r);
alert(i); // alerts "myVar as local variable from example"
alert(myVar); // alerts "other"
}
example();
Through the magic of closures, this gives you a way to simulate malloc.
function malloc() {
var i;
return createPointer(function() { return i; }, function(v) { i = v; });
}
var p = malloc(); // p points to a variable we just allocated from the heap
p.value = 2; // write a 2 into it
Your magic trick works too:
var flowers = new Misdirection(
createPointer(function() { return flowers; }, function(v) { flowers = v; }));
flowers.abracadabra();
alert(flowers);
function Misdirection(flowers) {
this.abracadabra = function() {
flowers.value = new Rabbit;
};
}
function Rabbit() {
this.toString = function() { return "Eh... what's up doc?" };
}
How can I achieve something similar to a pointer to a string in javascript?
I think I found a solution myself.
Could anyone comment if this is good practice or not?
It uses the new thing in ES6 where you can assign things [s1, s2] =
let s1 = "hi", s2 = "bye";
[s1, s2] = [s1, s2].map(s => s + (s.length < 3 ? "*" : ""));
Javascript pointer/reference craziness. Can someone explain this?
Following your example line by line:
a = {}
a
now references the new object.
b = a;
b
now references the same object that a
references. Note that it does not reference a
.
a['one'] = {};
The new object now has an index 'one'
that references another new object.
When you do
a = a['one'];
You are setting a
to refer to a['one']
, which is that new object you created when you did a['one'] = {}
. b
still references the object you created with a = {}
.
You are confusing the issue when you say "a
has lost its reference to b
" because a
does not refer to b
, nor vice versa. a
and b
refer to objects, and they can be made to refer to other objects. Like this:
With a = {}; b = a
, you get
a
\
\
{ }
/
/
b
Then with a['one'] = {}
you get
a
\
\
{ one: { } }
/
/
b
Then with a = a['one']
you get
a - - - -
\
{ one: { } }
/
/
b
Related Topics
Http Ajax Request via Https Page
Check If Every Element in One Array Is in a Second Array
Set a Cookie to Httponly via JavaScript
Manipulating Innerhtml Removes the Event Handler of a Child Element
Why Does !New Boolean(False) Equals False in JavaScript
Force Download Through Js or Query
Es6 Array Destructuring Weirdness
Relation Between Commonjs, Amd and Requirejs
Send Message to Specific Client with Socket.Io and Node.Js
How to Scroll to Specific Item Using Jquery
Should I Be Using Object Literals or Constructor Functions
Best Cross-Browser Method to Capture Ctrl+S with Jquery
How to Add a Tooltip to an Svg Graphic
Getting the Return Value of JavaScript Code in Selenium
JavaScript - Get Portion of Url Path
Canvas.Todataurl() Securityerror
How to Check in JavaScript If One Element Is Contained Within Another