在Javascript中通过引用传递字符串 [英] Pass a string by reference in Javascript
问题描述
我想创建一个字符串并通过引用传递它,以便我可以更改单个变量并将其传播到引用它的任何其他对象。
I want to create a string and pass it by reference such that I can change a single variable and have that propagate to any other object that references it.
Take这个例子:
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";
我希望能够实现这一目标:
I want to be able to have this happen:
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对字符串的引用表示度量标准是一个对象。
The MDC reference on strings says metric is an object.
我试过这个,这不是我想要的,但非常接近:
I've tried this, which is not what I want, but is very close:
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)
这里的重点:
- 我希望能够使用指标喜欢它是普通的字符串对象
- 我希望每个报告都引用同一个对象。
- I want to be able to use metric like it's a normal string object
- I want each report to reference the same object.
推荐答案
Javascript中的字符串已经通过引用传递 - 使用字符串调用过程不涉及复制字符串的内容。手头有两个问题:
Strings in Javascript are already passed "by reference" -- calling a procedure with a string does not involve copying the string's contents. There are two issues at hand:
- 字符串是不可变的。与C ++字符串相反,一旦创建了JavaScript字符串,就无法对其进行修改。
- 在JavaScript中,变量不是像C ++中那样静态分配的插槽。在您的代码中,
metric
是一个适用于两个完全独立的字符串变量的标签。
- Strings are immutable. In contrast to C++ strings, once a JavaScript string has been created it cannot be modified.
- In JavaScript, variables are not statically assigned slots like in C++. In your code,
metric
is a label which applies to two entirely separate string variables.
这是实现目标的一种方法,使用闭包来实现 metric
的动态范围:
Here's one way to achieve what you want, using closures to implement dynamic scoping of 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中通过引用传递字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!