Pass a string by reference in Javascript

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"


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";