文字列を作成して参照で渡し、単一の変数を変更して、それを参照する他のオブジェクトに伝播できるようにします。
この例を見てください:
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)
ここでの重要なポイント:
- 通常の文字列オブジェクトのようにメトリックを使用できるようにしたい
- 各レポートで同じオブジェクトを参照する必要があります。