Я хочу создать строку и передать ее по ссылке, чтобы я мог изменить одну переменную и распространить ее на любой другой объект, который ссылается на нее.
Возьмите этот пример:
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 на строки говорит, что метрика является объектом.
Я пробовал это, что не то, что я хочу, но очень близко:
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)
Важные моменты здесь:
- Я хочу использовать метрику , как будто это обычный строковый объект
- Я хочу, чтобы каждый отчет ссылался на один и тот же объект.