Given:
function shout(){ alert('Hello!'); }
var dasarray = [ shout ];
shout();
dasarray[0]();
shout = function(){ alert('World!'); }
shout();
dasarray[0]();
Output:
Hello!
Hello!
World!
Hello!
I would've expected that dasarray
received a reference to the function shout
, but sadly the 4th output is also hello. If I assume right, I was able to modify the shout
function correctly, but this leads to my assumption that the function was not passed by reference into dasarray
.
Instead of an array I already tried this example with an object:
dasarray = { myfunction: shout }
With the same, disappointing, result.
My intention is to have an array/object of/with functions, that are run in order and that can be extended in real time. For example extending the javascript with new functionality and adding additional function calls to existing events, that run in the correct order.
So, any idea how to put functions by reference into arrays/objects ?
Edit: Thanks for the good answers. I just wanted to explain that I chose Eli's answer, because it lead me to this setup:
zzz = {
calls: [],
shout: function(message) {
alert('Shouting: ' + message);
},
initialize: function () {
zzz.calls.push(['shout','Hello World']);
zzz.calls.push(['shout','this is']);
zzz.calls.push(['shout','my last shout!']);
zzz.run();
zzz.shout = function(){ alert('modified!'); };
zzz.run();
},
run: function () {
$.each(zzz.calls, function(){ zzz[this[0]](this[1]); }); // <- Using jQuery $.each here, just to keep it easy
}
};
zzz.initialize();
shout
is pointing at, the array still references the same function. – Shmiddty 2 days ago