I wrote this:
alert = function(x) {
alert(x);
};
alert(1);
And the firefox’s console displayed Too much recursion
And:
var x = alert;
alert = function(y) {
x(y);
};
alert(1);
Works perfectly.
Why the second way works and the first don’t?
And foo=foo; works. Isn’t alert=function(x){alert(x);}; the same as foo=foo;?
No. When you write:
you’re creating a function that, when called, will call itself endlessly until it runs out of stack space. The “alert” symbol you create will become a global variable. Inside the function, when it is invoked, the “alert” symbol will be resolved to that global variable.
Because of the semantics of JavaScript, references to variables in functions are resolved afresh on each invocation of the function. If, after defining that function, you did something like this:
then calling “otherAlert” would not cause an error, because at that point “alert” would be a different global function.