我想创建一个字符串并通过引用传递它,这样我就可以更改单个变量并将其传播到引用它的任何其他对象。
举个例子:
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说 metric 是一个对象。
我已经试过了,这不是我想要的,但非常接近:
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)
这里的要点:
- 我希望能够像使用普通字符串对象一样使用metric
- 我希望每个报告都引用同一个对象。
最佳答案
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";
关于javascript - 在 Javascript 中通过引用传递字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1308624/