Javascript does not support passing parameters by reference - Not true
Actually it does. Prototyping makes it possible to create true references to all kinds of javascript objects, including strings.
By true reference I mean when:
- Changes made to a variable or object
passed by reference is
reflected on the actual variable
beeing passed
- The change is seen by all
references to the same variable
- Everyone knowing the reference may
change the referenced variable
To create a true reference to a variable:
- Create a constructor function
- Prototype your reference variables on
the constructor
- DO NOT declare variables with the
same name inside the constructor
function!
- Create a change() function which
changes the prototyped variable or do
so directly
- Optional: Create a change() function-reference
inside your constructor which is set
to the ChangeRef() function uppon
creation
Changes made this way will be seen and may be changed by all other TestRef() objects
function TestRef(s) {
this.string = 'Own test-string: ' + s;
this.change = ChangeRef;
}
function ChangeRef(s) {
TestRef.prototype.refStr = s;
return TestRef.prototype.refStr;
}
r = 'RefStr';
TestRef.prototype.refStr = r; // PROTOTYPE => 'RefStr', copy of r
s = new TestRef('s'); // Obj.string = Own test-string: s, Obj.refStr = RefStr
o = new TestRef('o'); // Obj.string = Own test-string: o, Obj.refStr = RefStr
ChangeRef('ChangedStr'); // Change referenced string!
TestRef.prototype.refStr; // => ChangedStr, referenced string changed
r; // => RefStr, original string intact
x = new TestRef('x'); // Obj.string = Own test-string: x, Obj.refStr = ChangedStr. New sees changed string
s; // => Obj.string = Own test-string: s, Obj.refStr = ChangedStr. Old sees changed string
o; // => Obj.string = Own test-string: o, Obj.refStr = ChangedStr. Old sees changed string
s.change('Changed by local function');
x; // => Obj.string = Own test-string: o, Obj.refStr = Changed by local function