Is there a way to clone native functions in javasc

2019-07-21 15:28发布

问题:

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");
};

回答1:

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