Is there a way to clone native functions in javascript like window.alert or document.write
Asked Answered
N

1

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");
};
Nf answered 22/4, 2012 at 9:35 Comment(8)
Try running your code. You'll be surprised... ))Corrody
Here, why did you "know this won't work"?Bristle
window.alert() and document.wite() are not native - they are browser extensions to the ECMA standardPomerleau
@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.Nf
Yes, but your code doesn't change alert itself - it's simply not possible. It just binds the name "alert" to a new function.Corrody
@ValRedchenko Thanks for pointing out.You are right.I thought they may be native cause toString function on these objects print [native code].Nf
@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 ?Nf
@thg435 thanks +1 for this :)Nf
D
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

Dishonest answered 22/4, 2012 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.