Voglio creare una stringa e passarla per riferimento in modo tale da poter modificare una singola variabile e farla propagare a qualsiasi altro oggetto che la fa riferimento.Passare una stringa per riferimento in Javascript
Prendete questo esempio:
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";
Voglio essere in grado di avere questo accada:
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";
Perché non funziona?
Il MDC reference on strings indica che la metrica è un oggetto.
Ho provato questo, che non è quello che voglio, ma è molto vicino:
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 punti importanti qui:
- voglio essere in grado di utilizzare metrica come se fosse un normale oggetto stringa
- Voglio che ogni rapporto faccia riferimento allo stesso oggetto.
Ben fatto. Mi piace il meglio perché all'interno di Report, posso lavorare con la stringa con un minimo di disordine nella sorgente, cioè a(). CharAt (1) è molto più bello rispetto a String (a) .charAt (1) –
"Una chiusura è un blocco di codice che può essere referenziato (e passato in giro) con accesso alle variabili dell'ambito che lo racchiude. " da http://stackoverflow.com/a/5444581/483588 –
Questo non dimostra il passaggio per valore. Quello che sta facendo è semplicemente cambiare il valore della metrica, ovviamente registrerà il nuovo valore! var obj = { a: "a" }; var b = obj.a; console.log (obj.a); // a b = "b"; console.log (obj.a); // a – user1769128