我想要创建一个字符串并通过引用传递它,以便我可以更改单个变量并将其传播给引用它的任何其他对象。在JavaScript中传递参考字符串
拿这个例子:
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)
这里最重要的几点:
- 我希望能够使用指标就像它是一个普通的字符串对象
- 我希望每个报告引用同一个对象。
做得很好。我喜欢这是最好的,因为在报告中,我可以在源代码中使用最少的混乱字符串,即a()。charAt(1)比String(a).charAt(1) – 2009-08-20 20:58:12
更漂亮“闭包是可以通过访问封闭范围的变量来引用(并传递)的代码块。“从http://stackoverflow.com/a/5444581/483588 – 2012-12-22 18:09:00
这并不表明价值传递。这是做什么只是改变度量值,当然它会记录新的价值! var obj = { a:“a” }; var b = obj.a; console.log(obj.a); // a b =“b”; console.log(obj.a); // 一个 – user1769128 2015-06-04 16:04:12