Pass a string by reference in Javascript Pass a string by reference in Javascript javascript javascript

Pass a string by reference in Javascript


Strings in Javascript are already passed "by reference" -- calling a procedure with a string does not involve copying the string's contents. There are two issues at hand:

  • Strings are immutable. In contrast to C++ strings, once a JavaScript string has been created it cannot be modified.
  • In JavaScript, variables are not statically assigned slots like in C++. In your code, metric is a label which applies to two entirely separate string variables.

Here's one way to achieve what you want, using closures to implement dynamic scoping of metric:

function Report(a, b) {    this.ShowMe = function() { alert(a() + " of " + b); }}var metric = "count";var metric_fnc = function() { return metric; }var a = new Report(metric_fnc, "a"); var b = new Report(metric_fnc, "b"); a.ShowMe();  // outputs:  "count of a";metric = "avg";b.ShowMe();  // outputs:  "avg of b";


You can wrap the string in an object and modify the field the string is stored in.This is similar to what you are doing in the last example only without needing to change the functions.

var metric = { str : "count" } metric.str = "avg";

Now metric.str will contain "avg"


Closure?

var metric = new function() {    var _value = "count";    this.setValue = function(s) { _value = s; };    this.toString = function() { return _value; };};// snip ...a.ShowMe();metric.setValue("avg");b.ShowMe();c.ShowMe();

or making it a little more generic and performant:

function RefString(s) {    this.value = s;}RefString.prototype.toString = function() { return this.value; }RefString.prototype.charAt = String.prototype.charAt;var metric = new RefString("count");// snip ...a.ShowMe();metric.value = "avg";b.ShowMe();c.ShowMe();

If you don't close on the desired string variable, then I suppose the only other way would be to modify the ShowMe function, as in @John Millikin's answer or re-architect the codebase.