Note that there are some explanatory texts on larger screens.

plurals
  1. POPass a string by reference in Javascript
    primarykey
    data
    text
    <p>I want to create a string and pass it by reference such that I can change a single variable and have that propagate to any other object that references it.</p> <p>Take this example:</p> <pre><code>function Report(a, b) { this.ShowMe = function() { alert(a + " of " + b); } } var metric = new String("count"); var a = new Report(metric, "a"); var b = new Report(metric, "b"); var c = new Report(metric, "c"); a.ShowMe(); // outputs: "count of a"; b.ShowMe(); // outputs: "count of b"; c.ShowMe(); // outputs: "count of c"; </code></pre> <p>I want to be able to have this happen:</p> <pre><code>var metric = new String("count"); var a = new Report(metric, "a"); var b = new Report(metric, "b"); var c = new Report(metric, "c"); a.ShowMe(); // outputs: "count of a"; metric = new String("avg"); b.ShowMe(); // outputs: "avg of b"; c.ShowMe(); // outputs: "avg of c"; </code></pre> <p>Why doesn't this work?</p> <p>The <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String" rel="noreferrer">MDC reference on strings</a> says metric is an object.</p> <p>I've tried this, which is not what I want, but is very close:</p> <pre><code>var metric = {toString:function(){ return "count";}}; var a = new Report(metric, "a"); var b = new Report(metric, "b"); var c = new Report(metric, "c"); a.ShowMe(); // outputs: "count of a"; metric.toString = function(){ return "avg";}; // notice I had to change the function b.ShowMe(); // outputs: "avg of b"; c.ShowMe(); // outputs: "avg of c"; alert(String(metric).charAt(1)); // notice I had to use the String constructor // I want to be able to call this: // metric.charAt(1) </code></pre> <p>The important points here:</p> <ol> <li>I want to be able to use <strong>metric</strong> like it's a normal string object</li> <li>I want each report to reference the same object.</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload