2

What I want to do is change every alert in the code to a custom alert("you used alert");

var hardCodedAlert = alert; //I know this won't work.But what to do ?
window.alert=function(){
if(this.count == undefined)
this.count=0;
this.count=this.count+1;
if(this.count == 1)
hardCodedAlert("You used alert");
};
tshepang
  • 12,111
  • 21
  • 91
  • 136
Hariom Balhara
  • 832
  • 8
  • 19
  • Try running your code. You'll be surprised... )) – georg Apr 22 '12 at 09:36
  • 3
    [Here](http://jsfiddle.net/robertc/RM2XR/), why did you "know this won't work"? – robertc Apr 22 '12 at 09:44
  • 1
    window.alert() and document.wite() are not native - they are browser extensions to the ECMA standard – Val Redchenko Apr 22 '12 at 09:56
  • @thg435 yeah I am surprised :) Well, alert is a function(object).AFAIK objects are copied by reference .So change in alert function will be reflected in hardCodedAlert function also.So "You used Alert" alert should not have come. – Hariom Balhara Apr 22 '12 at 09:57
  • Yes, but your code doesn't _change_ `alert` itself - it's simply not possible. It just binds the name "alert" to a new function. – georg Apr 22 '12 at 10:00
  • @ValRedchenko Thanks for pointing out.You are right.I thought they may be native cause toString function on these objects print [native code]. – Hariom Balhara Apr 22 '12 at 10:03
  • @thg435 So what you mean is the whole thing about changing the source code of a function in javascript is wrong.Javascript just associates the name to a new function and calls new function in place of original function ? – Hariom Balhara Apr 22 '12 at 10:20
  • @thg435 thanks +1 for this :) – Hariom Balhara Apr 22 '12 at 10:50

1 Answers1

2

Yes, you can do (for example):

var oldalert = window.alert;
window.alert= function alert(t){
  alert.count = !alert.count ? 1 : alert.count + 1;
  oldalert(t+' - That\'s alert nr '+alert.count);
};

See this jsfiddle

KooiInc
  • 119,216
  • 31
  • 141
  • 177