jobo: pass by reference - verständnisproblem - und closure

Beitrag lesen

Hallo,

Crockford sagt weiter:
"One problem with that is that do_it could hold onto that function that I passed and use it again, perhaps some time when it's not to my advantage. Maybe I don't want to allow him to do that, that he can only store once into that variable. So I'll create a once function, and the once function will take a function and return a function which wraps it and which guarantees that it can only be called once. If you try to call it a second time, you'll get a null exception and it'll fail. So there's the function again. We're taking advantage of closure. When the function it returns is calm, it nulls out func, and that guarantees that it cannot be called usefully again. That allows us to have it called only once. Then I can take the result of storer and pass that once, and now we've got a function that can only be called once. Doing this, I've made a pretty big change to what do_it is able to do, without changing do_it. Because none of this is do_it's business."
Ich probiere das aus:

  
my_object = {  
	blah : "blah"  
}  
function do_it(inputs, callback) {  
	result = inputs;  
	callback(result);  
}  
function storer(obj, name) {  
	return function (result) {  
		obj[name] = result;  
	};  
}  
  
function once(func) {  
	return function () {  
		var f = func;  
		func = null;  
		return f.apply(this, arguments);  
	};  
}  
  
my_inputs = "fourthInput";  
do_it(my_inputs, once(storer(my_object, 'blah')));  
alert("first call do_it: " + my_object.blah); //fourthInput  
my_inputs = "fifthInput";  
do_it(my_inputs, once(storer(my_object, 'blah')));  
alert("second call do_it: " + my_object.blah);//fifthInput  
my_inputs = "sixthInput";  
do_it(my_inputs, storer(my_object, 'blah'));  
alert("third call do_it: " + my_object.blah); //sixthInput  
  

Aber weil func in der Funktion once ja ausgenullt wurde, dürfte es eigentlich ja nicht möglich sein, dass die Funktion ein zweites Mal ausgeführt wird. Anderseits ist das ja das Problem wie am Anfang: die Variable func existiert ja nur im Scope von once, hat also mit dem Parameter ja nix zu tun. Ich habe extra nochmal den Vortrag von Crockford angeschaut, ob der Code auch korrekt transcribiert wurde. Wurde er. Ist der Code falsch? Oder habe ich was falsch verstanden?

Gruß

jobo