我想创建一个字符串并通过引用传递它,这样我可以更改单个变量并将其传播到引用它的任何其他对象。

举个例子:

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

我希望能够发生这种情况:
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";

为什么不起作用?

MDC reference on strings说度量是一个对象。

我已经尝试过了,这不是我想要的,但是非常接近:
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)

这里的重点:
  • 我希望能够使用指标,就像它是普通的字符串对象
  • 我希望每个报表都引用相同的对象。
  • 最佳答案

    Javascript中的字符串已经“通过引用”传递了-用字符串调用过程并不涉及复制字符串的内容。目前有两个问题:

  • 字符串是不可变的。与C++字符串相反,一旦创建了JavaScript字符串,就无法对其进行修改。
  • 在JavaScript中,变量不是像C++中那样静态分配的插槽。在您的代码中,metric是一个标签,适用于两个完全独立的字符串变量。

  • 这是使用闭包实现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";
    

    10-07 19:10
    查看更多