funzione dinamica riscrittura può essere usato come una forma di lazy initialization, tuttavia c'è un problema:
function Foo() {...}
Foo.prototype = {
bar: function() {
//some initialized variables to close over
var a, b, c, ...;
Foo.prototype.bar = function() {
//do stuff with variables
};
Foo.prototype.bar.call(this);
}
};
Anche se questo codice è relativamente straight-forward per capire, e sarebbe stato utilizzato come:
var f = new Foo();
f.bar(); //initializes `bar` function
f.bar(); //uses initialized `bar` function
ha un problema nascosto:
var f = new Foo(),
g = {};
//passing by reference before the function was initialized will behave poorly
g.bar = f.bar;
f.bar(); //initializes `bar` function
g.bar(); //re-initializes `bar` function
f.bar(); //uses initialized `bar` function
g.bar(); //re-initializes `bar` function
E 'per questo motivo che ogni inizializzazione necessario per una funzione è in genere fatto utilizzando un modello di modulo:
function Foo() {...}
Foo.prototype = {
bar: (function() {
var a, b, c, ..., fn;
//some initialized variables to close over
fn = function() {
//do stuff with variables
};
return fn;
}())
};
Il modello modulo ha lo svantaggio di chiamare il codice di inizializzazione immediatamente, ma non avrà i problemi associati al riferimento alla funzione.
Perché ci dovrebbe essere una condizione di gara? Non ci sono più thread simultanei che eseguono JavaScript. – mellamokb
Oh duh. Grazie :) – Alan