Consider the code:
window.a = function(x){
var r = x*2;
window.a =alert; // redefines itself after first call
return r;
};
a('2 * 2 = '+a(2)); // doesn't work. it should've alerted "2 * 2 = 4"
This doesn't work either:
window.a = function(x){
alert(x);
window.a = function(x){ // redefines itself after first call
var r = x*2;
return r;
}
};
a('2 * 2 = '+a(2)); // doesn't work. it should've alerted "2 * 2 = 4"
As neither does this:
window.a = function(x){ alert(x); window.c = window.a; window.a = window.b; window.b = window.c; };
window.b = function(x){ var r = x*2; window.c = window.b; window.b = window.a; window.a = window.c; return r; };
a('2 * 2 = '+a(2)); // doesn't work.
And basically I've tried all possible ways and neither seem to do the job. Can someone please explain why?
You are successfully redefining the function, it's just that the expression calling it has already grabbed the old function reference: The first thing that happens in a call expression is that the thing defining what function to call is evaluated, see Section 11.2.3 of the specification:
Steps 1 and 2 occur before the function is redefined.
The solution is of course to make things happen in the order you expect (live example | source):
Side note: It's interesting that your first example works in Chrome (V8) (it also works in IE6's version of JScript; but then, JScript had lots of issues). It shouldn't work, and doesn't in Firefox (SpiderMonkey), Opera (Carakan), or IE9 (Chakra).
JavaScript has a strict left-to-right rule for order of evaluation of operator arguments. I am guessing that this includes the function-call operator, which means that the first
a
is evaluated before the expression.