Hey i dont know if that is possible but i want to set a given variable in js by reference.
What i want to do is, that each time i pass a string to t
Javascript does not support passing parameters by reference.
This link offers a good breakdown and some workarounds- Passing by Value or reference
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:
To create a true reference to a variable:
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
+=
works fine.
var str = "stack";
str += "overflow";
console.log(str); //alert(str); Use firebug!!
stackoverflow
Your code example will work just fine with +=
; complete example below. This suggests the problem you're having lies elsewhere.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function addstring(string)
{
document.getElementById('string').value += string;
}
</script>
</head>
<body><div>
<input type='text' id='string' value=''>
<br><input type='button' value='One' onClick="addstring('one');">
<input type='button' value='Two' onClick="addstring('two');">
<input type='button' value='Three' onClick="addstring('three');">
</div></body>
</html>
document.getElementById("string").value = document.getElementById("string").value + string;
You can clone the object by first converting it to JSON (watch out for circular references) and then parse it back again. Like so:
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
This uses the internal browser's JSON routines (safer & faster than using an external resource). If you simply must have backwards compatibility you can download the core JSON routines from JSON.org.