javascript - 在 Javascript 中通过引用传递字符串

标签 javascript string pass-by-reference

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

举个例子:

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)

这里的要点:

  1. 我希望能够像使用普通字符串对象一样使用metric
  2. 我希望每个报告都引用同一个对象。

最佳答案

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/

相关文章:

javascript - 委托(delegate)事件不能与 :not() selector 结合使用

javascript - 正确插入参数

c# - 删除字符串中特定字符后的字符,然后删除子字符串?

c++ - 模板按值传递或 const 引用或...?

javascript - 在对象数组中查找对象值 JavaScript

javascript - 使用 if 语句检查元素是否显示 : block jquery

string - 包含字符列表的所有固定长度子串(子集的任意 1 个排列)的最短字符串

在 C 中通过混合 char[] 和 int 创建字符串

java - 不可变和按值传递

c++ - 在 c/c++ 中何时按引用传递以及何时按值传递