我想创建一个字符串并通过引用传递它,这样我就可以更改单个变量并将其传播到引用它的任何其他对象。
拿这个例子:
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";
为什么这不起作用?
我试过这个,这不是我想要的,但非常接近:
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)
这里的要点:
- 我希望能够像使用普通字符串对象一样使用度量
- 我希望每个报告都引用同一个对象。